mysqlsqldatabasenexusdb

Sum multiple rows of SQL


Here's my code:

SELECT Invoice_detail.Xtype, 
       Invoice_detail.Totallineprice
FROM Invoice_detail Invoice_detail
      INNER JOIN Invoice_head Invoice_head ON 
     (Invoice_head.idx = Invoice_detail.Xinvoicehead)
WHERE ( Invoice_detail.Totallineprice <> 0 )
       AND ( Invoice_head.xCurrency = 1 )
ORDER BY Invoice_detail.Xtype

Which returns:

301  -  50
291  -  56.25
291  -  75
70   -  (125)
70   -  50
70   -  75

How do I get this code to sum so my result looks more like this?

301  -  50
291  -  131.25
70   -  0

Thanks for your help!


Solution

  • try this query, use Sum to sum up the second column(Invoice_detail.Totallineprice) for the group of first column(Invoice_detail.Xtype) using GROUP BY

    SELECT Invoice_detail.Xtype, 
           SUM(Invoice_detail.Totallineprice)
    FROM Invoice_detail Invoice_detail
          INNER JOIN Invoice_head Invoice_head ON 
         (Invoice_head.idx = Invoice_detail.Xinvoicehead)
    WHERE ( Invoice_detail.Totallineprice <> 0 )
           AND ( Invoice_head.xCurrency = 1 )
    GROUP BY  Invoice_detail.Xtype
    ORDER BY Invoice_detail.Xtype