我试图在同一年的同一个月获得不同的总和,只是为了获得不同类型的总和。尝试使用此代码:
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
和ETC。
答案 0 :(得分: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
答案 1 :(得分:0)
因为每个月都有不同的价值。在Field year尝试Group By。
答案 2 :(得分:0)
你基本上在寻找PIVOT。 MySql没有PIVOT功能,但你仍然可以做到这一点。以下是MySql中PIVOT的示例: