2014-11-03 163 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。這使用一個技巧來獲取作者的最後更新。訣竅是將所有作者連接在一起,按更新時間排序。然後選擇列表的第一個元素。