简体   繁体   English

Mysql计数查询按年和月水平分组

[英]Mysql count query by Grouping Year and Month horizontal

I am new to mysql query and i am stuck on getting query. 我是mysql查询的新手,但我一直在获取查询。 Basically, i want the date to group as Year and month (Jan'17, Feb'17...) in horizontal way (column) as shown in Image below. 基本上,我希望日期以水平方式(列)分组为年和月(Jan'17,Feb'17 ...),如下图所示。 计数

Data are shown in image below: 数据如下图所示:

资料图片

Please help to create query. 请帮助创建查询。

You can do conditional aggregation - once per login_id and then overall and then union both the results. 您可以进行条件汇总-每个login_id一次,然后进行整体汇总,然后合并两个结果。

Select login_idindex,
  Sum(date_format(visitdate, '%Y%m')  = '201701' ) as jan_17,
  Sum(date_format(visitdate, '%Y%m')  = '201702' ) as feb_17,
  . . .,
  Count(*) as total
From your_table
Where visitdate between ? and ?
Group by login_idindex

Union all

Select null,
  Sum(date_format(visitdate, '%Y%m')  = '201701' ) as jan_17,
  Sum(date_format(visitdate, '%Y%m')  = '201702' ) as feb_17,
  . . .,
  Count(*) as total
From your_table
Where visitdate between ? and ?;

Replace ? 更换? with actual dates or remove the where clause if you are working with all the dates. 包含实际日期,如果要处理所有日期,请删除where子句。

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

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