2012-06-04 30 views
0

表:date,user,order_type。使用嵌套查詢,分組依據和計數的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 
... 

回答

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