【问题标题】:How can we merge the results of two queries have group by and two conditions我们如何合并两个查询的结果有group by和两个条件
【发布时间】:2015-06-13 15:28:06
【问题描述】:

我有这两张桌子:(游戏)

和(轮)桌:

我想获取游戏 ID、回合数以及 player1 获胜的回合数。我创建了两个这样的 sql 查询:

但我想在一张表中获得所有结果。我怎样才能将结果组合成这样:

【问题讨论】:

    标签: sql sql-server group-by


    【解决方案1】:

    你可以使用条件聚合

    SELECT game_id, COUNT(*) AS roundsCount, 
           COUNT(CASE WHEN winner = player1_id THEN 1 END) As p1WinsCount   
    FROM games AS g
    INNER JOIN rounds AS r ON g.Id = r.game_id
    GROUP BY game_id
    

    Demo here

    【讨论】:

    • 非常感谢,这帮助我得到了结果。我们称之为使用方式(case, then .. end)。有什么好的网址可以了解更多吗?
    • @zuhair 当在SUMCOUNT 等函数中使用CASE 表达式时,这称为条件聚合。网上有很多关于这个主题的资源。以this 为例。
    • 使用 count() 函数时不需要'*'。请指定列名。
    • @Mukesh 在这种情况下不会有任何区别
    【解决方案2】:

    您可以将 2 个单独查询的结果与派生表相结合:

    select
      A.gameId, 
      A.roundsCount,
      B.p1WinsCount
    from
      (
         select g.Id as gameId, count(r.Id) as roundsCount
         from game g, rounds r
         where g.Id = r.game_id
         group by g.Id
       ) A,
       (
         select g.Id as gameId, count(r.Id) as p1WinsCount
         from game g, rounds r
         where r.winner = g.player1_id
         group by g.Id
        ) B
    where
      A.gameId = B.gameId
    

    但在这种情况下,您也可以简单得多:

     select 
       g.Id as gameId, 
       count(r.Id) as roundsCount, 
       sum(case when r.winner = g.player1_id then 1 else 0 end) as p1WinsCount
     from 
       game g
       join rounds r on g.Id = r.game_id
     group by 
       g.Id
    

    【讨论】:

    • 非常感谢您的回复。这工作正常:)
    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2011-04-05
    • 2015-08-15
    相关资源
    最近更新 更多