GROUP BY,值可以是2列中的任何一列

时间:2014-01-24 20:08:17

标签: sql count group-by

好的,我真的不确定如何解决这个SQL问题所以我会继续解释它......

我有一个包含以下列的表:

gameId, winnerPlayerId, winnerFactionId, loserPlayerId, loserFactionId

现在,我想构建一个查询,给定一个factionId,输出以下数据:

playerId, totalGamesPlayedAsFaction

在这里让我感到困惑的是,我表中的每一行都需要计算两次,一次是为了输家,一次是为了赢家......所以我不能使用简单的GROUP BY winnerPlayerId。

我觉得好像我的问题不是特别清楚,解决方案可能很简单......

3 个答案:

答案 0 :(得分:2)

您需要以某种方式“复制”数据。最典型的方式是使用union all

select . . .
from ((select gameId, winnerPlayerId as PlayerId, winnerFactionId as FactionId
       from table t
      ) union all
      (select gameId, loserPlayerId as PlayerId, loserFactionId as FactionId
       from table t
      )
     ) t
group by PlayerId, FactionId;

答案 1 :(得分:1)

看起来像是一个受欢迎的自我加入的工作

select playerid, count(*) total
from player p left join game winner on p.playerid = winner.winnerplayerid
left join game loser on p.playerid = loser.loserplayerid
etc

这将帮助您入门。您必须自己处理过滤器和空值。

答案 2 :(得分:0)

迷人且多用途的方式是做一些不同的方式,但快速和肮脏的方式类似于union all方法。完整的SQL将是:

select games.PlayerId, COUNT(games.gameId)
from ((select gameId, winnerPlayerId as PlayerId, winnerFactionId as FactionId
       from tblGame winners
       ) 
      union all
       (select gameId, loserPlayerId as PlayerId, loserFactionId as FactionId
       from tblGame losers
        )
     ) games
where games.FactionId = 'x'
group by games.PlayerId