2017-09-27 90 views
0

使用此查詢我試着總結兩個SUM函數的結果:如何SUM結果兩個SUM SQL?

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult, 
SUM(result + noresult) 
from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day` 

我嘗試這樣做,在這條線:

SUM(result + noresult) 
+0

你爲什麼不環繞另一個查詢查詢做SUM(結果+ noresult) –

+2

使用'SUM(IF(狀態= '1',1,0))+ SUM(IF(狀態= '2',1,0))'而不是別名。 –

回答

1

其他幾個人都表示,你不能在你的SELECT語句中使用別名。但是,爲了保持清潔,您可以結合這兩種情況,而不是總結SUM這兩個字段。

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult, 
SUM(if(status = '1' OR status = '2', 1, 0)) AS newcolumn 
from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day` 
+0

@ Joel Coehoorn的答案可能會更清晰,如果你想將兩個以上的這些加在一起。 – kchason

2

不能在選擇列使用別名,你必須重複代碼

select 
DAY(created_at) AS day, 
SUM(if(status = '1', 1, 0)) AS result, 
SUM(if(status = '2', 1, 0)) AS noresult, 
SUM(if(status = '1', 1, 0)) + SUM(if(status = '2', 1, 0)) AS all_result 

from `clients` where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) group by `day` 

必須重複代碼,因爲不同的SQL子句以特定順序處理(首先從那裏再然後通過選擇和和組....等),所以在選擇解析別名的時刻不可用於SQL引擎

+0

承認,它看起來很糟糕 – OPV

+0

@ PM77-1謝謝額外刪除.. – scaisEdge

+1

@OPV。可能只是SQL子句按特定順序處理(先從那裏再選擇,然後按....分組),所以在選擇解析時,別名不可用於sql引擎 – scaisEdge

3

試試這個:

select 
    DAY(created_at) AS day, 
    SUM(if(status = '1', 1, 0)) AS result, 
    SUM(if(status = '2', 1, 0)) AS noresult, 
    SUM(if(status in ('1', '2'), 1, 0)) 
from `clients` 
where `doctor_id` = 2 and MONTH(created_at) = MONTH(CURRENT_TIMESTAMP) 
group by `day`