匹配预测游戏的SQL聚合百分比

时间:2014-04-20 09:09:30

标签: sql sql-server tsql

我正在做一个预测游戏,我有下表

{MatchID, Team1Score, Team2Score}

如何找出team1或team2的投票百分比是多少?

我想出了以下内容:

SELECT        COUNT(dbo.Predictions.ID) AS Team1Wins, COUNT(Predictions_2.ID) AS 
Team1Loss, COUNT(Predictions_1.ID) AS Total
FROM            dbo.Predictions CROSS JOIN
                         dbo.Predictions AS Predictions_2 CROSS JOIN
                         dbo.Predictions AS Predictions_1
WHERE        (dbo.Predictions.Team1Score > dbo.Predictions.Team2Score) AND (Predictions_2.Team1Score < Predictions_2.Team2Score)

但我认为应该有更好的方法来做到这一点

1 个答案:

答案 0 :(得分:1)

我现在面前没有任何实例所以请原谅任何错别字

;with Winner as
(
select
    MatchID
   ,count(*) as number
   ,sum(case when Team1Score > Team2Score then 1 else 0) as Team1
   ,sum(case when Team1Score < Team2Score then 1 else 0) as Team2
   ,sum(case when Team1Score = Team2Score then 1 else 0) as Draw
from dbo.Predictions
group by MatchID
)
select
    MatchID
   ,Team1 * 100 / number as PercentTeam1
   ,Team2 * 100 / number as PercentTeam2
   ,Draw * 100 / number as PercentDraw
from Winner
order by MatchID;

HTH