2014-11-03 148 views
0

这里有一个表:MySQL查询GROUP BY/ORDER BY计数

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 

我想计数的每个项目每个状态的总数,以及项目的最新日期/作者

结果应该是这样的:

计数(状态)= 2时项= a和状态= 1个

计数(状态)= 0当项= a和状态= 2

计数(状态)= 0时,项=和状态= 3

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?

+0

你真的需要这种支点吗?你是否只希望知道一定数量的状态值? – 2014-11-03 15:03:06

回答

0

你想一些其他信息做一个支点。我建议这种做法:

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; 

棘手的部分是最后一列,author。这使用一个技巧来获取作者的最后更新。诀窍是将所有作者连接在一起,按更新时间排序。然后选择列表的第一个元素。