【问题标题】:Create two aggregated virtual tables from one table and join从一个表创建两个聚合的虚拟表并连接
【发布时间】: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;

【问题讨论】:

标签: sql join aggregate-functions


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多