Mysql 带有嵌套查询、分组依据和计数的SQL查询
表:日期、用户、订单类型 order_type枚举了4个值:音乐、书籍、电影、艺术 我需要一个查询,返回订单总数和按用户分组的每种订单类型的数量:Mysql 带有嵌套查询、分组依据和计数的SQL查询,mysql,sql,Mysql,Sql,表:日期、用户、订单类型 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(*)
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