3

Is there a more elegant way of doing this:

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 

I hate the SUM section with a passion, there must be a better way of doing this.

User enters the @NumOfGames and @Team as parameters to the stored procedure. It then checks the goals table to see if a team won, drew or lost. A win is 1 point, a draw is 0.5 and a loss is 0. I want to output the sum of these numbers, divide them by the NumOfGames and multiply by 100 to get a success rate.

4

1 に答える 1

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 

記録のために、比較 "Fixture.HomeTeamID <> @Team" は case ステートメントでは不要であり、読みやすくするためだけに存在します (そして、iota の効率が低下します)。case ステートメントは、WHEN 句を順番に評価し、一致する最初のものを選択することによって機能します。

Microsoft に IIF() を削除するよう請願できますか? ;-)

于 2012-08-15T01:21:56.473 に答える