表:日期、用户、订单类型。
order_type 是 4 个值的枚举:音乐、书籍、电影、艺术。
我需要一个查询来返回按用户分组的每个订单类型的总订单数和计数:
user, total, music, movies, books, art
--------------------------------------
Adam, 10, 5, 2, 3, 0
Smith, 33, 10, 3, 15,2
mary, 12,6,1,3,2
...
SELECT user,
COUNT(*) AS total,
SUM(order_type='music') AS music,
SUM(order_type='movies') AS movies,
SUM(order_type='books') AS books,
SUM(order_type='art') AS art
FROM my_table
GROUP BY user
select user, count(*) as total,
sum(case when order_type = 'music' then 1 else 0) end as music,
sum(case when order_type = 'movies' then 1 else 0) end as movies,
sum(case when order_type = 'books' then 1 else 0) end as books,
sum(case when order_type = 'art' then 1 else 0) end as art
from t
group by user