2012-06-04 4 views
0

테이블 : 날짜, 사용자, order_type.중첩 쿼리, 그룹화 및 카운트가있는 SQL 쿼리

order_type은 music, books, movies, art의 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 
:

나는 총 주문 횟수 및 사용자별로 그룹화 각 주문 유형의 수를 반환하는 쿼리가 필요합니다