3

我有以下 MS SQL 查询,它交叉引用三个表(tTeam、tPlayer 和 tScores)来获得按 Net score 和 Team 排序的总“Net score”、“Gross score”和“Position”。

SELECT TeamID, Team, NetScore, Gross,  
CASE WHEN cnt > 1 THEN 'T' + CAST(rnk AS VARCHAR(5)) 
         ELSE CAST(rnk AS VARCHAR(5))
END Pos
FROM (
SELECT tTeam.TeamID, 
       tTeam.Title AS Team, 
       SUM(CONVERT(INT, tScores.Net_Score)) AS NetScore, 
       SUM(CONVERT(INT, tScores.Out_Score) + CONVERT(int, tScores.In_Score)) AS Gross, 
       rank() OVER ( ORDER BY SUM(CONVERT(INT, tScores.Net_Score))) rnk, 
       COUNT(*) OVER ( PARTITION BY SUM(CONVERT(INT, tScores.Net_Score))) cnt
FROM tScores INNER JOIN tPlayer ON tScores.PlayerID = tPlayer.PlayerID INNER JOIN tTeam ON tPlayer.TeamID = tTeam.TeamID 
WHERE tTeam.TournamentID = 13
GROUP BY tTeam.TeamID, tTeam.Title ) temp
ORDER BY NetScore, Team

该查询效果很好,但是(这是我需要帮助的地方),它正在按团队计算所有球员的净得分和总得分,而我需要做的只是按团队计算“4 个最低球员的净得分和总得分”只要。

我花了最后一天半的时间用这个把头发拉出来,任何帮助都将不胜感激。

提前致谢!

4

1 回答 1

0

如果我理解正确,您只想将每个玩家的四个最低分数相加,您可以使用另一组 row_numbers 来隔离最低分数。我不认为 rn_gross 是必要的(基于 rank() 函数),但我仍然包含它。如果不需要单独编号,则从总和中删除条件并添加and lowestScores.rn_net <= 4到 where 子句。

; with lowestScores as
(
  select *,
         ROW_NUMBER() over (PARTITION by PlayerID
                            order by CONVERT(INT, Net_Score)) rn_net,
         ROW_NUMBER() over (PARTITION by PlayerID
                            order by CONVERT(INT, Net_Score) + CONVERT(int,In_Score)) rn_gross
    from tScores                            
),
temp as
(
  SELECT tTeam.TeamID, 
         tTeam.Title AS Team, 
         SUM(CASE WHEN rn_net <= 4 THEN CONVERT(INT, lowestScores.Net_Score) END) AS NetScore, 
         SUM(CASE WHEN rn_gross <= 4 THEN CONVERT(INT, lowestScores.Out_Score) END
           + CASE WHEN rn_gross <= 4 THEN CONVERT(int, lowestScores.In_Score) END) AS Gross, 
         rank() OVER ( ORDER BY SUM(CASE WHEN rn_net <= 4 THEN CONVERT(INT, lowestScores.Net_Score) END)) rnk, 
         COUNT(*) OVER ( PARTITION BY SUM(CASE WHEN rn_net <= 4 THEN CONVERT(INT, lowestScores.Net_Score) END)) cnt
    FROM lowestScores 
   INNER JOIN tPlayer 
      ON lowestScores.PlayerID = tPlayer.PlayerID 
   INNER JOIN tTeam 
      ON tPlayer.TeamID = tTeam.TeamID 
   WHERE tTeam.TournamentID = 13
   GROUP BY tTeam.TeamID, tTeam.Title
)
SELECT TeamID, Team, NetScore, Gross,  
       CASE WHEN cnt > 1 
            THEN 'T' + CAST(rnk AS VARCHAR(5)) 
            ELSE CAST(rnk AS VARCHAR(5))
        END Pos
  FROM temp
 ORDER BY NetScore, Team
于 2012-09-08T00:09:11.947 回答