2012-06-04 60 views
1

我想在同一年得到與當月不同的總和,只是爲了得到不同類型的總和。使用此代碼嘗試:同一月份兩個不同的SUMS

SELECT a.invoice_type, year(a.date) AS Year, 
     date_format(a.date, '%M') AS `month` , 
     Sum(x.amount * x.price) AS sum FROM records x 
JOIN paper_invoice a ON x.invoice_id = a.invoice_id 
WHERE year(a.date) = '2012' 
GROUP BY a.invoice_type, Year(a.date) , Month(a.date) LIMIT 0 , 30  

,但它給出了不同行的結果:

http://www.part.lt/img/1505f0f13172922150febede85ddbf0925.png

但我需要它看起來像:

Year | Month | SUM_GRYNAIS  | SUM_PAVEDIMU 
2012 | January | 7597.14997705445 | 58740.2800849304 

等。

回答

0

因爲每個月都有不同的值。在場地一年試試Group By。

1

試試這個:

SELECT Year, Month, 
MAX(CASE WHEN invoice_type = 'GRYNAIS' THEN sum END) As Sum_GRYNAIS 
MAX(CASE WHEN invoice_type = 'PAVEDIMU' THEN sum END) As SUM_PAVEDIMU 
FROM 
(
SELECT a.invoice_type, year(a.date) AS Year, 
date_format(a.date, '%M') AS `month` , Sum(x.amount * x.price) AS sum 
FROM records x JOIN paper_invoice a ON x.invoice_id = a.invoice_id 
WHERE year(a.date) = '2012' GROUP BY a.invoice_type, Year(a.date) , 
Month(a.date) LIMIT 0 , 30  

) 
GROUP BY Year, Month 
+0

感謝這一個工作。完善! :) –

相關問題