简体   繁体   English

在MySQL中按年和月分组

[英]Group By Year and Month in MySQL

I have a table with 25 date columns. 我有一个包含25个日期列的表格。 Now i am building an application in PHP and have to show a month and year based summary. 现在,我正在用PHP构建应用程序,并且必须显示基于月份和年份的摘要。 I have mentioned the Source table layout and expected Summary table below. 我在下面提到了“源”表布局和预期的“摘要”表。

Here ID represents each row. 这里的ID代表每一行。 Source table ID will be used in the summary table. 源表ID将在摘要表中使用。 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. 在这里我想提一下,我在源表上大约有3万行。

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

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. 表示填空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM