我想做的是:
SELECT
RaceResults.IdPilot,
SUM(RaceResults.Score)-MIN(RaceResults.Score)-MIN2(RaceResults.Score) AS TotalScore
FROM RaceResults
GROUP BY RaceResults.IdPilot
如何从分数列中获得第二个最小值(上述代码中的MIN2)?
答案 0 :(得分:0)
您可以使用基于窗口函数Row_Number()
的条件求和()示例强>
Declare @YourTable Table ([IdPilot] int,[Score] int)
Insert Into @YourTable Values
(1,15)
,(1,15)
,(1,20)
,(1,50) -- The sum of example is 100 and the bottom 2 equal 30
Select A.IdPilot
,TotalScore = sum(Score)-sum(case when rn<=2 then Score end)
From (
Select *
,RN = Row_Number() over (Partition By idPilot Order by Score)
From @YourTable
) A
Group By A.IdPilot
<强>返回强>
IdPilot TotalScore
1 70