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

时间:2017-05-10 03:03:59

标签: mysql

我是mysql查询的新手,我仍然坚持获取查询。基本上,我希望日期以水平方式(列)分组为年份和月份(Jan' 17,Feb' ...),如下图所示。 Count

数据如下图所示:

Data image

请帮助创建查询。

1 个答案:

答案 0 :(得分:0)

你可以进行条件聚合 - 每个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 ?;

?替换为实际日期,或者如果您使用所有日期,请删除where子句。