【发布时间】:2022-01-24 06:38:17
【问题描述】:
我想建立一个基于一个表的查询。我想从这张表中创建两个基于计数聚合查询的虚拟表。在我的示例中,它将原始表拆分为一个表,其中计算每位玩家的 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;
【问题讨论】:
-
“基于”和“在 1 次查询中完成”没有任何特别的含义。 PSminimal reproducible exampleHow to Ask
标签: sql join aggregate-functions