我有这个表结构
CREATE TABLE `table_detail` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`status` CHAR(2) NOT NULL,
`dateTime_updated` DATETIME NOT NULL,
PRIMARY KEY (`id`),
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
我想要指定具有7,6和4的用户状态
从2015-09-07 06:00:00 - 2015-09-11 20:00:00
7 =有效,6 =无效,4 =已删除
预期产出
+---------+--------+----------+---------+
| user_id | active | inactive | deleted |
+---------+--------+----------+---------+
| 55 | 2 | 3 | 0 |
| 26 | 4 | 6 | 3 |
| 15 | 3 | 7 | 7 |
| 24 | 6 | 3 | 3 |
+---------+--------+----------+---------+
提前谢谢。
答案 0 :(得分:0)
您可以使用条件聚合。您需要做的就是在select子句中添加SUM(condition)
列,并按user_id
值分组:
SELECT user_id,
SUM(status = 7) AS active,
SUM(status = 6) AS inactive,
SUM(status = 4) AS deleted
FROM table_detail
WHERE dateTime_updated BETWEEN '2015-09-07 06:00:00' AND '2015-09-11 20:00:00'
GROUP BY user_id;