dongtan9518 2017-06-02 18:45
浏览 146
已采纳

在MySQL中按年和月分组

I have a table with 25 date columns. Now i am building an application in PHP and have to show a month and year based summary. I have mentioned the Source table layout and expected Summary table below.

Here ID represents each row. Source table ID will be used in the summary table. The summary table will be created per year. I need some help to prepare this summary table. Here I would like to mention that i will have around 30K rows on the source table.

Source Table:

ID  |  DATE 1      |  DATE 2        |   DATE 3
--------------------------------------------------
1   |  2017-01-14  |   2017-01-19   |   2017-01-25
2   |              |   2017-03-19   |   2017-03-25
3   |  2017-03-15  |                |   2017-05-25
4   |  2017-04-24  |   2017-05-19   |   
5   |  2017-04-10  |   2017-06-19   |   2017-07-25
6   |  2017-05-11  |   2017-06-19   |   2017-08-25

Summary Table

ID  |   YEAR | JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC
------------------------------------------------------------------------------------
1   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0 
2   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0 
3   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0 
4   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0 
5   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0 
6   |   2017 |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |  0
  • 写回答

1条回答 默认 最新

  • duanguane1670 2017-06-02 18:57
    关注

    You need to unpivot the data and re-aggregate it. The structure of the query is:

    select id, year(date) as yyyy,
           sum( month(date) = 1 ) as Jan,
           sum( month(date) = 2 ) as Feb,
           . . .
           sum( month(date) = 12 ) as Dec
    from ((select id, date1 as date from source) union all
          (select id, date2 as date from source) union all
          . . .
          (select id, date25 as date from source) 
         ) d
    where date is not null
    group by id, year(date)
    order by id, year(date);
    

    The . . . means fill in the blanks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条