我想在一列上使用case語句,並在條件滿足時計算另一列的聚合。在一列上使用CASE語句並計算另一列的聚合
,我查詢看上去像這樣的樣本數據表(用於酒店爲例):
| date | customer_name | customer_id | expense_type | billed_amount |
| 08-02 | John Doe | 1 | personal | 120.00 |
| 08-03 | John Doe | 1 | personal | 80.00 |
| 08-04 | John Doe | 1 | corporate | 205.00 |
| 08-02 | Adam Smith | 2 | corporate | 400.00 |
| 08-03 | Adam Smith | 2 | personal | 300.00 |
| 08-06 | Adam Smith | 2 | corporate | 150.00 |
下面是SQL查詢我寫道:
Select
customer_name
, customer_id
, case when expense_type = 'personal' then sum(billed_amount) else 0 end as personal_bill
, case when expense_type = 'corporate' then sum(billed_amount) else 0 end as corporate_bill
From payments
Where date > '08-01'
Group by 1, 2
錯誤消息我得到是:
Column "expense_type" must appear in the GROUP BY clause or be used in an aggregate function
當我嘗試組3列(以及1和2),我收到此錯誤消息:
Aggregates not allowed in GROUP BY clause
最後,下面示出所希望的結果表:
| customer name | customer_id | personal_bill | corporate_bill |
| John Doe | 1 | 200.00 | 205.00 |
| Adam Smith | 2 | 300.00 | 550.00 |
一種解決方案,我能想到是創建限制在哪裏部分中的「expense_type」兩個不同的子查詢(即where expense_type ='personal'),然後在主查詢中查詢它們,但這是很多類似的代碼,只有一行的區別。你能幫我以有效的方式寫這個查詢嗎?謝謝!
didn'瞭解「過濾器」語法;謝謝! – Joe