简体   繁体   English

mysql查询分组/按计数排序

[英]mysql query group by/order by count

Here is a table: 这是一张桌子:

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

I would like to count the total number of each status for each Item, and the latest date/author of the items 我想计算每个项目的每种状态的总数,以及项目的最新日期/作者

The result should be like this: 结果应该是这样的:

count(status) =2 when item=a and status=1 当item = a并且status = 1时count(status)= 2

count(status) =0 when item=a and status=2 当item = a并且status = 2时count(status)= 0

count(status) =0 when item=a and status=3 当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

How to write the sql ? 怎么写sql?

You want to do a pivot along with some other information. 您想与其他一些信息一起进行透视。 I would suggest this approach: 我建议这种方法:

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;

The tricky part is the last column, author . 棘手的部分是最后一列, author This uses a trick to get the author for the last update. 这使用技巧来获取作者的最新更新。 The trick is to concatenate all the authors together, ordered by the update time. 诀窍是将所有作者串联在一起,并按更新时间排序。 Then choose the first element of the list. 然后选择列表的第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM