使用MySql和DB2获取一年中所有月份分组的数据

时间:2016-11-09 06:24:18

标签: mysql db2

下面是我的查询

    SELECT DISTINCT e2.status as status, e2.year as year, e2.month as month,e2.Jan,e2.Feb,e2.Mar,e2.Apr,e2.May,e2.Jun,e2.Jul,e2.Aug,e2.Sep,e2.Oct,e2.Nov, e2.Dece, e2.countTotal FROM tranx_history e1 INNER JOIN ( 

   SELECT YEAR(e.create_dt) AS year, MONTH(e.create_dt) AS month,
   SUM(CASE WHEN MONTH(e.create_dt) = 01 THEN 1 ELSE 0 END) AS Jan,
   SUM(CASE WHEN MONTH(e.create_dt) = 02 THEN 1 ELSE 0 END) AS Feb,
   SUM(CASE WHEN MONTH(e.create_dt) = 03 THEN 1 ELSE 0 END) AS Mar,
   SUM(CASE WHEN MONTH(e.create_dt) = 04 THEN 1 ELSE 0 END) AS Apr,
   SUM(CASE WHEN MONTH(e.create_dt) = 05 THEN 1 ELSE 0 END) AS May,
   SUM(CASE WHEN MONTH(e.create_dt) = 06 THEN 1 ELSE 0 END) AS Jun,
   SUM(CASE WHEN MONTH(e.create_dt) = 07 THEN 1 ELSE 0 END) AS Jul,
   SUM(CASE WHEN MONTH(e.create_dt) = 08 THEN 1 ELSE 0 END) AS Aug,
   SUM(CASE WHEN MONTH(e.create_dt) = 09 THEN 1 ELSE 0 END) AS Sep,
   SUM(CASE WHEN MONTH(e.create_dt) = 10 THEN 1 ELSE 0 END) AS Oct,
   SUM(CASE WHEN MONTH(e.create_dt) = 11 THEN 1 ELSE 0 END) AS Nov,
   SUM(CASE WHEN MONTH(e.create_dt) = 12 THEN 1 ELSE 0 END) AS Dece,
   SUM(CASE WHEN MONTH(e.create_dt) >= 01 AND MONTH(e.create_dt) <= 12 THEN 1 ELSE 0 END) as countTotal,
   e.trnx_status as status
   from tranx_history e
   GROUP BY  e.trnx_status, MONTH(e.create_dt),YEAR(e.create_dt) ) e2 ON YEAR(e1.create_dt)  = e2.year AND MONTH(e1.create_dt) = e2.month ORDER BY e2.year asc, e2.month asc 

对于上面的查询,我们得到的输出首先是按Jan分组,然后在下一行按2分组,即使状态和年份相同

我希望输出Jan和Feb具有相同的状态和年份,而不是在不同的行中

0 个答案:

没有答案