简体   繁体   中英

MySQL count types per day

So I have a table

| date | name | type |

I want to transform the data to make a table that counts how many names of each type appeared on each date.

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

I had two types, so I did this

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

But I feel like this is an overkill, and becomes too repetitive for more types.

So let's say I have 4 types. I'm sure there is something nicer I'm missing.

You can conditionally aggregate w/ a case statement:

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

Add additional case statements for additional types.

The above shows zeros for dates w/ no type a or type b values, which matches the logic of your outer joins. If you didn't want such dates at all you could add this where clause:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM