mysql 查询分组依据/排序依据计数

标签 mysql group-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

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

结果应该是这样的:

当 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/

相关文章:

group-by - 对 SELECT 中的 NUMC 字段求和

php - 如何对共享相同首字母的一组行进行计数和求和

mysql - sql语句中的多个where子句?

php - 使用 OOP PHP ORM 选择查询

MySQL delete语句基于sub-select有多个返回值同时为每个唯一值保留500条记录

sql - MySQL - 计算两个日期时间之间的净时间差,同时排除休息时间?

python - "ValueError: Length of values does not match length of index"尝试修改 pandas groupby 的列值时

mysql - 我们可以使用列的 order by 而不使用该列的 group by 来编写 oracle 查询吗

python - groupby 对象 pandas 的绝对值平均值

mysql - Magento错误: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded;