我有3个列标题为account_id,game_date和queue_type。我必须显示一个帐户每个queue_type播放了多少个游戏。 Atm我能够显示在一段时间内每个帐户玩的游戏总数,但是我如何深入挖掘总数而不是显示队列类型的列?
SELECT account_id, COUNT(*) as GamesPlayed FROM Games
WHERE DATE (game_date) BETWEEN '2012-01-01' AND '2013-01-01'
GROUP BY account_id
HAVING COUNT(account_id) > 2;
这给了我两个列,即帐号ID,然后是旁边播放的总游戏数,但不是总数,而是我希望在顶部作为列标题播放的游戏类型。总共有4种游戏类型。
答案 0 :(得分:3)
这称为条件聚合。您可以计算不同的类型,并为它们分配所需的列名称。 (更改每个数据的queue_type值)
SELECT account_id
,COUNT(case when queue_type = 'A' THEN 1 END) as A
,COUNT(case when queue_type = 'B' THEN 1 END) as B
,COUNT(case when queue_type = 'C' THEN 1 END) as C
,COUNT(case when queue_type = 'D' THEN 1 END) as D
FROM Games
WHERE game_date >= '2012-01-01' AND game_date <='2013-01-01'
GROUP BY account_id
或更简单
SELECT account_id
,SUM(queue_type = 'A') as A
,SUM(queue_type = 'B') as B
,SUM(queue_type = 'C') as C
,SUM(queue_type = 'D') as D
FROM Games
WHERE game_date >= '2012-01-01' AND game_date <='2013-01-01'
GROUP BY account_id