这是一个表格:
ID Item status updatetime author
1 a 1 2014-01-02 Mike
2 a 1 2014-02-01 Jack
3 b 2 2014-01-10 John
4 b 1 2014-10-10 Ben
5 b 2 2014-01-11 Sam
6 c 3 2014-01-02 Aron
7 c 1 2014-11-01 Aron
8 c 1 2014-10-20 Max
9 d 3 2014-10-20 Mike
我想统计每个项目的每种状态的总数,以及项目的最新日期/作者
结果应该是这样的:
当 item=a 且 status=1 时,count(status) =2
当 item=a 且 status=2 时,count(status) =0
当 item=a 且 status=3 时,count(status) =0
Item status_1 status_2 status_3 Latestupdate author
a 2 0 0 2014-02-01 Jack
b 1 2 0 2014-10-10 Ben
c 2 0 1 2014-11-01 Aron
d 0 0 1 2014-10-20 Mike
sql怎么写?
最佳答案
您想要与一些其他信息一起进行数据透视。我建议采用这种方法:
select item,
sum(status = 1) as status_1,
sum(status = 2) as status_2,
sum(status = 3) as status_3,
max(updatetime) as LatestUpdate,
substring_index(group_concat(author order by updatetime desc), ',', 1) as author
from table t
group by item;
棘手的部分是最后一栏,作者
。这使用了一个技巧来获取最后更新的作者。诀窍是将所有作者连接在一起,按更新时间排序。然后选择列表的第一个元素。
关于mysql 查询分组依据/排序依据计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716453/