在MySQL中按年和月分组

时间:2017-06-02 18:45:04

标签: php mysql sql

我有一个包含25个日期列的表。现在我正在使用PHP构建应用程序,并且必须显示基于月份和年份的摘要。我已经提到了Source表格布局和下面的预期汇总表。

此处Django==1.8.6 Django-Select2==4.3.1 Pillow==3.0.0 South==1.0.2 Unidecode==0.04.18 YURL==0.13 aldryn-apphooks-config==0.2.6 aldryn-boilerplates==0.7.3 aldryn-categories==1.0.1 aldryn-common==1.0.0 aldryn-newsblog==1.0.9 aldryn-people==1.1.2 aldryn-reversion==1.0.1 aldryn-translation-tools==0.2.1 argparse==1.4.0 backport-collections==0.1 cmsplugin-filer==1.0.0 dj-database-url==0.3.0 django-admin-sortable==1.8.4 django-appconf==1.0.1 django-appdata==0.1.4 django-autoslug==1.8.0 django-ckeditor-filebrowser-filer==0.1.1 django-classy-tags==0.6.2 django-cms==3.1.3 django-durationfield==0.5.2 django-easy-select2==1.3 django-filer==1.0.2 django-mptt==0.7.4 django-parler==1.5.1 django-phonenumber-field==0.7.2 django-polymorphic==0.7.2 django-reversion==1.8.7 django-sekizai==0.8.2 django-sortedm2m==1.3.2 django-taggit==0.17.3 django-treebeard==3.0 djangocms-admin-style==1.0.5 djangocms-column==1.5 djangocms-file==0.1 djangocms-flash==0.2.0 djangocms-googlemap==0.3 djangocms-inherit==0.1 djangocms-installer==0.7.9 djangocms-link==1.6.2 djangocms-picture==0.1 djangocms-style==1.5 djangocms-teaser==0.1 djangocms-text-ckeditor==2.7.0 djangocms-video==0.1 easy-thumbnails==2.2.1 gunicorn==19.4.3 html5lib==0.9999999 lxml==3.5.0 phonenumbers==7.1.1 python-dateutil==2.4.2 python-slugify==1.1.4 pytz==2015.7 simplejson==3.8.0 six==1.10.0 tzlocal==1.2 vobject==0.6.6 wheel==0.24.0 wsgiref==0.1.2 代表每一行。源表ID将在摘要表中使用。摘要表将每年创建。我需要一些帮助来准备这个汇总表。在这里我想提一下,我将在源表上有大约30K行。

来源表:

ID

汇总表

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

1 个答案:

答案 0 :(得分:3)

您需要取消数据并重新聚合。查询的结构是:

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);

. . .表示填空。