从一个 table 创建两个聚合虚拟 table 并加入

Create two aggregated virtual tables from one table and join

我想建立一个基于 table 的查询。从这个 table 我想创建两个基于计数聚合查询的虚拟 table。在我的示例中,它会将原始的 table 拆分为一个 table,其中每个玩家的 Xbox 游戏数被计算在内,另一个是每个玩家的 Playstation 游戏数被计算在内。然后根据PlayerID连接查询结果。

create table data (PlayerID text, game text, platform text);

insert into data (PlayerID, game, platform) values
('Player1', 'Fifa', 'Playstation'),
('Player1', 'Tekken', 'Playstation'),
('Player1', 'Gears of War', 'Xbox'),
('Player1', 'Ninja Gaiden', 'Playstation'),
('Player2', 'Gears of War', 'Xbox'),
('Player1', 'Metal Slug Anthology', 'Playstation'),
('Player1', 'Metal Gear V', 'Playstation'),
('Player2', 'Halo', 'Xbox'),
('Player3', 'Street Fighter', 'Playstation'),
('Player3', 'Madden NFL', 'Playstation'),
('Player1', 'Final Fantasy', 'Xbox'),
('Player2', 'Ratchet & Clank', 'Playstation');

结果应如下所示:

| PlayerID | playedPlaystationGames | playedXBoxGames |
|----------|------------------------|-----------------|
|  Player1 |                      5 |               2 |
|  Player2 |                      1 |               2 |
|  Player3 |                      2 |               0 |

这 3 个步骤应该在 1 个查询中完成:

Select PlayerID, Count(platform)as playedPlaystationGames, platform
From Data AS TablePlaystation
Group By PlayerID, platform
Having platform='Playstation';

Select PlayerID, Count(platform)as playedXBoxGames, platform
From Data AS TableXBox
Group By PlayerID, platform
Having platform='Xbox';

SELECT data.PlayerID, TableXBox.PlayedXBoxGames, TablePlaystation.playedPlaystationGames
FROM data
RIGHT JOIN (TablePlaystation
    RIGHT JOIN TableXBox
    ON TablePlaystation.PlayerID = TableXBox.PlayerID)
ON TablePlaystation.PlayerID = data.PlayerID;

使用Group By

SELECT PlayerID,
          SUM(CASE WHEN platform = 'Playstation' THEN 1 ELSE 0 END) AS playedPlaystationGames,
          SUM(CASE WHEN platform = 'Xbox' THEN 1 ELSE 0 END) AS playedXBoxGames 
FROM data
GROUP BY PlayerID

演示在 sqlfiddle

或者我不推荐的其他方法

SELECT T1.PlayerID,playedPlaystationGames,playedXBoxGames
FROM

  (Select PlayerID, Count(platform)as playedPlaystationGames, platform
  From Data AS TablePlaystation
  Group By PlayerID, platform
  Having platform='Playstation') t1
  
  LEFT JOIN
  
  (Select PlayerID, Count(platform)as playedXBoxGames, platform
  From Data AS TableXBox
  Group By PlayerID, platform
  Having platform='Xbox') t2 ON T1.PlayerID = T2.PlayerID