带有嵌套查询,分组依据和计数的SQL查询

时间:2012-06-04 11:38:12

标签: mysql sql

  

表:日期,用户,order_type。

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
...

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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
相关问题