在MySQL中需要某种“条件分组”

时间:2010-06-02 00:48:05

标签: sql mysql group-by

我有文章表:

id | type | date
-----------------------
 1 | A    | 2010-01-01
 2 | A    | 2010-01-01
 3 | B    | 2010-01-01

字段type可以是A,B或C.

我需要运行一个报告,每天会返回每种类型的文章数量,如下所示:

date       | count(type="A") | count(type="B") | count(type="C")
-----------------------------------------------------
2010-01-01 | 2               | 1               | 0
2010-01-02 | 5               | 6               | 7

目前,我为每种类型运行3个查询,然后手动合并结果

select date, count(id) from article where type="A" group by date

是否可以在一个查询中执行此操作? (在纯sql中,没有存储过程或类似的东西)。

由于

2 个答案:

答案 0 :(得分:8)

SUM和CASE的组合应该做ya

select date
    , sum(case when type ='A' then 1 else 0 end) as count_type_a 
    , sum(case when type ='B' then 1 else 0 end) as count_type_b
    , sum(case when type ='C' then 1 else 0 end) as count_type_c 
from article group by date

答案 1 :(得分:1)

编辑: Alex's answer above使用的方法比此答案更好。我将它留在这里只是因为它也以另一种方式满足了这个问题:


您应该可以使用子查询,如下所示:

SELECT    DATE(a.date) as date,
          (SELECT COUNT(a1.id) FROM articles a1 WHERE a1.type = 'A' AND a1.date = a.date) count_a,
          (SELECT COUNT(a2.id) FROM articles a2 WHERE a2.type = 'B' AND a2.date = a.date) count_b,
          (SELECT COUNT(a3.id) FROM articles a3 WHERE a3.type = 'C' AND a3.date = a.date) count_c
FROM      articles a
GROUP BY  a.date;

测试用例:

CREATE TABLE articles (id int, type char(1), date datetime);

INSERT INTO articles VALUES (1, 'A', '2010-01-01');
INSERT INTO articles VALUES (2, 'A', '2010-01-01');
INSERT INTO articles VALUES (3, 'B', '2010-01-01');
INSERT INTO articles VALUES (4, 'B', '2010-01-02');
INSERT INTO articles VALUES (5, 'B', '2010-01-02');
INSERT INTO articles VALUES (6, 'B', '2010-01-03');
INSERT INTO articles VALUES (7, 'B', '2010-01-01');
INSERT INTO articles VALUES (8, 'C', '2010-01-05');

结果:

+------------+---------+---------+---------+
| date       | count_a | count_b | count_c |
+------------+---------+---------+---------+
| 2010-01-01 |       2 |       2 |       0 |
| 2010-01-02 |       0 |       2 |       0 |
| 2010-01-03 |       0 |       1 |       0 |
| 2010-01-05 |       0 |       0 |       1 |
+------------+---------+---------+---------+
4 rows in set (0.00 sec)