2014-02-15 86 views
0

我正在使用以下查詢來返回帳單總額和稅金的總額,稅額和總額。但問題是因爲我使用sum()它只返回第一個如何檢索所有行和總計?查詢返回兩列總和

SELECT sum(
      at_salesbill.`billedTotal` + at_salesbill.`billedTotalTax` 
      ) as grantTotal, 
     at_salesbill.`billedTotal` AS at_salesbill_billedTotal, 
     at_salesbill.`billedTotalTax` AS billedTotalTax, 
    FROM at_salesbill 
WHERE at_salesbill.`billGuid` = 44; 

回答

1

你可以只添加值獲得的總和:

SELECT (at_salesbill.`billedTotal`+at_salesbill.`billedTotalTax`) as grantTotal, 
     at_salesbill.`billedTotal` AS at_salesbill_billedTotal, 
     at_salesbill.`billedTotalTax` AS billedTotalTax, 
from at_salesbill 
where at_salesbill.`billGuid` = 44; 

然後,你可以做一個把戲,以獲得總與值一起,假設你在該行中有一個獨特的id

SELECT at_salesbill.id, 
     sum(at_salesbill.`billedTotal`+at_salesbill.`billedTotalTax`) as grantTotal, 
     at_salesbill.`billedTotal` AS at_salesbill_billedTotal, 
     at_salesbill.`billedTotalTax` AS billedTotalTax, 
from at_salesbill 
where at_salesbill.`billGuid` = 44 
group by at_salesbill.id with rollup; 

在這裏,sum()沒有什麼意思 - 因爲每個組中都有一行。但是,with rollup將添加一個總列,其中idNULL

SELECT (case when at_salesbill.id is NULL then 'total' else '' end), 
     sum(at_salesbill.`billedTotal`+at_salesbill.`billedTotalTax`) as grantTotal, 
     at_salesbill.`billedTotal` AS at_salesbill_billedTotal, 
     at_salesbill.`billedTotalTax` AS billedTotalTax, 
from at_salesbill 
where at_salesbill.`billGuid` = 44 
group by at_salesbill.id with rollup; 
+0

謝謝...好訣竅:) – Firu