MySQL每天的计数类型

时间:2014-08-02 00:31:02

标签: mysql sql database

所以我有一张桌子

| date | name | type |

我想转换数据以制作一个表格,计算每个日期出现的每种类型的名称。

| date | count(type_a) | count(type_b) | ....

我有两种类型,所以我做了这个

SELECT t0.date, type_a, type_b 
FROM
(SELECT DISTINCT date from my_table) AS t0
LEFT JOIN (SELECT date, COUNT(name) AS type_a
           FROM my_table
           WHERE type='type_a'
           GROUP BY date) AS t1
    ON t0.date = t1.date
LEFT JOIN (SELECT date, COUNT(name) AS type_b
           FROM my_table
           WHERE type='type_b'
           GROUP BY date) AS t2 
    ON t0.date = t2.date

但我觉得这是一种矫枉过正,对于更多类型而言,它变得过于重复。

所以,让我说我有4种类型。我确信有一些更好的东西我不知道。

1 个答案:

答案 0 :(得分:3)

您可以有条件地汇总w / case语句:

select date,
       sum(case when type = 'type_a' then 1 else 0 end) as type_a,
       sum(case when type = 'type_b' then 1 else 0 end) as type_b
from   tbl
group by date

为其他类型添加其他案例陈述。

上面显示的是日期的零,没有类型a或类型b值,它们匹配外部联接的逻辑。如果您根本不想要这样的日期,可以在where where子句中添加:

where  type in ('type_a','type_b')