2015-12-07 19 views
2

我有两列数量+日期,如何创建一个有月份名称的列和显示每月总和(数量)的其他列?sql如何创建一个月份的列并显示它们的总和

Date  |Qty 
----  |--- 
2014-1-2 | 5 
2014-1-3 | 9 
2014-1-4 | 100 
2014-1-5 | 200 
. 
. 
. 




result : 

Month |Qty 
----  |--- 
JAN  | 500 
Feb  | 900 
Mar  | 200 
. 
. 

我已经得到了数量,但无法获得月份列怎么做呢?

我为此查询这样

SELECT SUM(case when Date BETWEEN '2014-1-1' and '2014-2-1' then Qty else 0 end) as Qty from table 

UNION 

SELECT SUM(case when Date BETWEEN '2014-2-1' and '2014-3-1' then Qty else 0 end) as Qty from table 

UNION 

SELECT SUM(case when Date BETWEEN '2014-3-1' and '2014-4-1' then Qty else 0 end) as Qty from table 

UNION 

SELECT SUM(case when Date BETWEEN '2014-4-1' and '2014-5-1' then Qty else 0 end) as Qty from table 

UNION 

SELECT SUM(case when Date BETWEEN '2014-5-1' and '2014-6-1' then Qty else 0 end) as Qty from table 
UNION 

SELECT SUM(case when Date BETWEEN '2014-6-1' and '2014-7-1' then Qty else 0 end) as Qty from table 

UNION 

SELECT SUM(case when Date BETWEEN '2014-7-1' and '2014-8-1' then Qty else 0 end) as Qty from table 

UNION 

. 
. 

回答

3

尝试GROUP BY DATE_FORMAT

SELECT SUM(Qty) as Qty,DATE_FORMAT(Date, '%b') Month from table 
GROUP BY DATE_FORMAT(Date,'%Y-%m') 
+1

谢谢合作! – phpnet

相关问题