在使用一个查询的结果时使用逻辑

时间:2016-06-13 15:07:18

标签: sql sql-server

我在下面有一个子查询,每个团队可以随机输出11支球队(1 GK,4 DF,4 MF和2 FW)。

SELECT * FROM(
    SELECT pl.*,
           ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
    FROM(
        SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber
        FROM dbo.Fixture f
        INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
        INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
        INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
        WHERE f.WeekNumber = 1) 
        pl) po
WHERE (po.position = 'GK' and po.rnk = 1) OR 
      (po.position = 'DF' and po.rnk <= 4) OR
      (po.position = 'MF' and po.rnk <= 4) OR
      (po.position = 'FW' and po.rnk <= 2) 

以下是输出内容的示例:

MDN documentation

然后我有一个夹具查询:SELECT * FROM dbo.Fixture及以下是输出的内容:

enter image description here

现在这是我为逻辑而奋斗的地方。我希望以某种方式将他们各自球队内的球员联系起来,在一周的比赛中对抗他们的对手。拥有最高玩家权重的团队(基于本周玩的11名玩家)将赢得比赛。我不知道如何实际做到这一点。我如何将这些球员与他们的球员结合起来就是我想要问的所以我可以总结他们的总体球员权重以确定获胜者。

更新:

SELECT * FROM(
    SELECT pl.*,
           ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
    FROM(
        SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber, SUM(PlayerWeighting)
        FROM dbo.Fixture f
        INNER JOIN dbo.Team t ON f.HomeTeamID = t.TeamID
        INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
    WHERE f.WeekNumber = 1) pl) po
WHERE (po.position = 'GK' and po.rnk = 1) OR 
      (po.position = 'DF' and po.rnk <= 4) OR
      (po.position = 'MF' and po.rnk <= 4) OR
      (po.position = 'FW' and po.rnk <= 2) 
     GROUP BY TeamID

1 个答案:

答案 0 :(得分:0)

为什么不在SUM(PlayerWeighting)对第一个查询进行teamId分组,并在dbo.Fixture之后将其加入HomeTeamID or AwayTeamID? 您将通过FixtureId获得两行

Select TeamID, SUM(PlayerWeighting) as TeamWeight
FROM (
    SELECT * FROM(
        SELECT pl.*,
               ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
        FROM(
            SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber
            FROM dbo.Fixture f
            INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
            INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
            INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
            WHERE f.WeekNumber = 1) 
            pl) po
    WHERE (po.position = 'GK' and po.rnk = 1) OR 
          (po.position = 'DF' and po.rnk <= 4) OR
          (po.position = 'MF' and po.rnk <= 4) OR
          (po.position = 'FW' and po.rnk <= 2) ) as T
GROUP BY T.TeamID