高尔夫评分SQL查询

时间:2012-09-07 23:44:14

标签: sql sql-server

我有以下MS SQL查询交叉引用三个表(tTeam,tPlayer和tScores)以获得由Net score和Team排序的总“净得分”,“总得分”和“位置”。

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个最低玩家的净值和总得分” “仅限团队。

我花了最后一天半用这个把头发拉出来,非常感谢任何帮助。

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果我理解你只想为每个玩家的四个最低分数求和,你可以使用另一组row_numbers来隔离最低分数。我不认为rn_gross是必要的(基于rank()函数),但我还是把它包括在内。如果不需要单独的编号从sums中删除条件,并将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