我是mysql查询的新手,我仍然坚持获取查询。基本上,我希望日期以水平方式(列)分组为年份和月份(Jan' 17,Feb' ...),如下图所示。
数据如下图所示:
请帮助创建查询。
答案 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子句。