0

テーブル:date、user、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
...
4

2 に答える 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
于 2012-06-04T11:54:35.400 に答える
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
于 2012-06-04T11:56:50.837 に答える