Pull columns from derived table and sum them in one MySQL SELECT statement

后端 未结 1 2000
情深已故
情深已故 2021-01-27 10:13

I need to pull column data from two tables, run calculations on the data with the result saved as an alias, and then sum those results into other alias\' to display in a php tab

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 11:18

    I had a spelling mistake and a formatting issue. By formatting the final data instead of formatting within the embedded SELECT statement, my table data was accurate.

    Successful CODE:

    $sql = "SELECT x.company, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as sgtotqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.avgsqftrev), 2) as avgsqftrevenue, FORMAT(SUM(x.avgunitrev), 2) as avgunitrevenue FROM (SELECT t1.company, t1.stagestatus, t1.shippeddate, t1.id, TRIM(LEADING '$' FROM t1.totalprice) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotquantity, SUM(t2.width * t2.height * t2.quantity ) /144 AS sgtotalsqft, (TRIM(LEADING '$' FROM t1.totalprice)/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (TRIM(LEADING '$' FROM t1.totalprice) / SUM(t2.quantity)) AS avgunitrev
    FROM invoices AS t1 INNER JOIN lineitems AS t2 ON t1.id = t2.invoiceid
    WHERE (t2.invoiceid = t1.id)
    GROUP BY t1.id) x
    WHERE x.stagestatus='Complete'
    GROUP BY x.company ASC";
    

    Thank you!!!

    0 讨论(0)
提交回复
热议问题