mysql统计一个字段的多种状态
2015-09-08 15:55
537 查看
假如我有下面的表:
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,每一种status的个数为多少,同时记录器最新的时间和作者,结果如下:
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
select item,
sum(case when status = 1 then 1 else 0 end) as status_1,
sum(case when status = 2 then 1 else 0 end) as status_2,
sum(case when status = 2 then 1 else 0 end) as status_3
max(update time) as Latestupdate,
author
from table
group by item, status_1, status_2, status_3
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,每一种status的个数为多少,同时记录器最新的时间和作者,结果如下:
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
select item,
sum(case when status = 1 then 1 else 0 end) as status_1,
sum(case when status = 2 then 1 else 0 end) as status_2,
sum(case when status = 2 then 1 else 0 end) as status_3
max(update time) as Latestupdate,
author
from table
group by item, status_1, status_2, status_3
相关文章推荐
- mysql 查询语句
- ActiveReports如何使用MySQL数据库
- Ubuntu 安装mysql和简单操作
- Mysql innodb_flush_log_trx_commit 简单调优
- MySQL技术之旅--随意写在前面的话
- MySQL允许远程连接的设置总结
- mysql limit使用方法
- MySQL字符串函数substring:字符串截取
- MYSQL命令
- mysql主主关系配置
- MySQL索引类型&建立索引的时机&索引的不足之处
- 命令行修改MySQL数据库密码
- MySQL CMake参数说明手册
- MYSQL-统计查询
- mysqli
- 解决您配置文件中的设置 (空密码的 root) 与 MySQL 默认管理员账户对应。
- 安装hive后使用mysql作为数据库无法正常启动问题
- MyBatis+MySQL 返回插入的主键ID
- MYSQL的三种注释
- 【R】R语言windows下连接MySQL