是否有更优雅的方式:
SELECT TOP (@NumOfGames)
(SUM(IIF(Fixture.HomeTeamID = @Team
,IIF(Fixture.Goals.FullTimeHomeGoals > Fixture.Goals.FullTimeAwayGoals
,1
,IIF(Fixture.Goals.FullTimeHomeGoals < Fixture.Goals.FullTimeAwayGoals, 0, 0.5)
) --IsHomeTeam
,IIF(Fixture.Goals.FullTimeAwayGoals > Fixture.Goals.FullTimeHomeGoals
,1
,IIF(Fixture.Goals.FullTimeAwayGoals < Fixture.Goals.FullTimeHomeGoals, 0, 0.5)
) --IsAwayTeam
)) / @NumOfGames) * 100 AS Result
FROM
Fixture.Fixture
INNER JOIN
Fixture.Goals ON Fixture.Goals.FixtureID = Fixture.Fixture.FixtureID
WHERE
HomeTeamID = @Team
OR
AwayTeamID = @Team
我非常讨厌SUM部分,必须有更好的方法来做到这一点。
用户输入@NumOfGames和@Team作为存储过程的参数。然后它会检查目标表,看看一支球队是赢了,是否赢了。胜利是1分,平局是0.5,损失是0.我想输出这些数字的总和,除以NumOfGames并乘以100得到成功率。
答案 0 :(得分:10)
呸。 Microsoft似乎已将IIF添加到SQL Server 2012中。无论如何,您可能会发现标准SQL方式更具吸引力。这将使用CASE语句:
SELECT TOP (@NumOfGames)
(SUM(case when Fixture.HomeTeamID = @Team and
Fixture.Goals.FullTimeHomeGoals > Fixture.Goals.FullTimeAwayGoals
then 1.0
when Fixture.HomeTeamID = @Team and
Fixture.Goals.FullTimeHomeGoals = Fixture.Goals.FullTimeAwayGoals
then 0.5
when Fixture.HomeTeamID = @Team
then 0.0
when Fixture.HomeTeamID <> @Team and
Fixture.Goals.FullTimeAwayGoals > Fixture.Goals.FullTimeHomeGoals
then 1.0
when Fixture.HomeTeamID <> @Team and
Fixture.Goals.FullTimeAwayGoals = Fixture.Goals.FullTimeHomeGoals
then 0.5
else 0.0
end) / @NumOfGames) * 100 AS Result
FROM
Fixture.Fixture
INNER JOIN
Fixture.Goals ON Fixture.Goals.FixtureID = Fixture.Fixture.FixtureID
WHERE
HomeTeamID = @Team
OR
AwayTeamID = @Team
对于记录,在case语句中不需要比较“Fixture.HomeTeamID&lt;&gt; @Team”,只是为了使它更具可读性(而且效率更低)。 case语句的工作原理是按顺序评估WHEN子句,然后选择第一个匹配的子句。
我们可以请求微软删除IIF()吗? ; - )