2014-05-01 61 views
0

我正在查詢一張名爲Events的表,該錶針對黃卡和紅卡(它是足球應用程序)預訂量最多的玩家。黃色是值得1點和紅色是值得3.在具有多個計數的查詢中一起添加兩個引用

我有這個疑問:

SELECT player_id, first_name, last_name, slug, 
     SUM(CASE WHEN event_type.name = 'Yellow Card' THEN 1 ELSE 0 END) AS yellowAmount, 
     SUM(CASE WHEN event_type.name = 'Red Card' THEN 3 ELSE 0 END) AS redAmount 
FROM event 
INNER JOIN matches ON event.match_id = matches.id 
INNER JOIN player  ON event.player_id = player.id 
INNER JOIN event_type ON event.event_type_id = event_type.id 
WHERE matches.league_id = 94 
    AND (event_type.name = "Yellow Card" OR event_type.name = "Red Card") 
GROUP BY player_id; 

你如何添加yellowAmountredAmount在一起,並使用該命令的結果?

我已經試過,但我得到一個未知的列錯誤:

SELECT player_id, first_name, last_name, slug, 
     SUM(CASE WHEN event_type.name = 'Yellow Card' THEN 1 ELSE 0 END) AS yellowAmount, 
     SUM(CASE WHEN event_type.name = 'Red Card' THEN 3 ELSE 0 END) AS redAmount, 
     SUM(yellowAmount + redAmount) AS total 
FROM event 
INNER JOIN matches ON event.match_id = matches.id 
INNER join player  ON event.player_id = player.id 
INNER JOIN event_type ON event.event_type_id = event_type.id 
WHERE matches.league_id = 94 
    AND (event_type.name = "Yellow Card" OR event_type.name = "Red Card") 
GROUP BY player_id 
ORDER BY total DESC; 
+0

sum(case when event_type.name ='Yellow Card'then 1 else 0 end)+ sum(case when event_type.name ='Red Card'then 3 else 0 end) – Strawberry

回答

1

有此不起作用有兩個原因:

  1. 條款yellowAmountredAmount中不存在基礎表;你已經將它們定義爲SELECT子句本身的別名。 MySQL(以及大多數其他關係數據庫)不支持在SELECT子句的其他地方從SELECT子句的一部分使用別名。

  2. 即使MySQL允許您引用先前定義的別名,在這種情況下,它是沒有意義的。 yellowAmountredAmount已經是SUMED量;爲什麼/你會如何總結他們? SUM操作只能應用於您在GROUP BY操作中彙總的行內存在的值。

所以您必須重複整個CASE語句中建議@草莓的評論,或者你必須嵌套在另一個查詢,什麼也不做,但添加兩個期望的數值範圍之內整個查詢:

select player_id, first_name, last_name, slug, yellowAmount + redAmount as total 
from (SELECT player_id, first_name, ... 
     FROM event 
     INNER JOIN ... 
     ... 
     GROUP BY player_id) a 
order by total desc; 

請注意,在MySQL中,您可以使用以允許在ORDER BY子句中使用SELECT子句中的total別名(儘管並非所有SQL實現都支持該子句)。

相關問題