2014-06-10 52 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)。 –