我该如何计算状态

时间:2015-10-27 03:13:34

标签: mysql

我有这个表结构

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 |
+---------+--------+----------+---------+

提前谢谢。

1 个答案:

答案 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;