2014-06-10 54 views
1

出于某种原因,我不能简单地介绍一些代码。MySql为体育联盟的.pct划分

我想在下面的代码中将“赢”分为“玩”,这样在我的输出中,如果您赢得了4场比赛中的2场比赛,则显示为.500?

确定它很简单,放置可能是关键,但我无法为我的生活摸索它!

$result = mysql_query(" 
    select team, 
    count(*) played, 
    count(case when HomeScore > AwayScore then 1 end) wins, 
    count(case when AwayScore > HomeScore then 1 end) lost, 
    count(case when HomeScore = AwayScore then 1 end) draws, 
    sum(HomeScore) ptsfor, 
    sum(AwayScore) ptsagainst, 
    sum(HomeScore) - sum(AwayScore) goal_diff, 
    sum(case when HomeScore > AwayScore then 3 else 0 end + case 
    when HomeScore = AwayScore then 1 else 0 end) score  
    from (select 
     HomeTeam team, 
     HomeScore, 
     AwayScore 
    from Game 
     union all 
    select AwayTeam, 
     AwayScore, 
     HomeScore 
    from Game) a 
    group by team 
    order by wins desc, 
     draws desc, 
    lost asc, 
    goal_diff desc;"); 

感谢

回答

0

又一个计算列添加到查询,像这样:因为我假定分数将是整数

select team, 
count(*) played, 
count(case when HomeScore > AwayScore then 1 end) wins, 
(cast(count(case when HomeScore > AwayScore then 1 end) as decimal(8,2)/cast(count(*) as decimal(8,2)) percentage, 
.... -> Rest of the query goes here 

铸造完成。如果没有施法,将会失去准确性,即2/4将在没有施法的情况下返回0。

+0

我现在得到“警告:mysql_fetch_assoc()预计参数1是资源,布尔在/home/peterborough/www/www/leaguetable.php给出的41行”,这是我的,而语句,其工作先前:while($ row = mysql_fetch_assoc($ result)) { echo“”; 回声“​​”。 $ row ['team']。 “”; 回声“​​”。 $ row ['wins']。 “”; 回声“​​”。 $ row ['lost']。 “”; \t echo“​​”。 $ row ['percentage']。 “”; echo“”; } echo“”; – MongoUK

0

请尝试以下的查询。这利用了MySQL的行为自动将boolean表达式转换为int。所以这意味着没有CASE语句(漂亮的查询以牺牲可移植性为代价)。此外,SUM(3*win + draw) score等部件在视觉上看起来更像您的分数计算公式。计算没问题pct

SELECT team 
    , COUNT(*) played 
    , SUM(win) wins 
    , SUM(loss) lost 
    , SUM(win)/count(*) pctWon 
    , SUM(draw) draws 
    , SUM(SelfScore) ptsfor 
    , SUM(OpponentScore) ptsagainst 
    , SUM(SelfScore) - SUM(OpponentScore) goal_diff 
    , SUM(3*win + draw) score 
FROM (
     SELECT team 
    , SelfScore 
    , OpponentScore 
    , SelfScore < OpponentScore win 
    , SelfScore > OpponentScore loss 
    , SelfScore = OpponentScore draw 
     FROM (
     SELECT HomeTeam team, HomeScore SelfScore, AwayScore OpponentScore 
     FROM Game 
     union all select AwayTeam, AwayScore, HomeScore 
     FROM Game 
     ) a 
) b 
GROUP BY team 
ORDER BY wins DESC, draws DESC, lost ASC, goal_diff DESC; 
+0

看起来更像这样,虽然对于已经赢得4/5比赛的球队来说,它显示为.4000,而它应该是.800(需要弄清楚如何让它变成小数点后3位而不是4) – MongoUK

+0

嗯,在我的测试中,我有一个4/5胜的球队,正确显示0.8000。我不明白它是如何变成0.4000的。我只是将SQL Fiddle中的架构放在http://sqlfiddle.com/#!9/47dc9/1 ......就小数精度而言,这实际上更多地在演示文稿/客户端方面。您将控制从您的应用程序显示多少个地方(例如:PHP)。 –