2016-05-25 67 views
0

我試圖寫一個返回下面列的查詢問題:我的WHERE子句(SQL)

owner_id, 
number_of_concluded_bookings, 
number_of_declined_bookings, 
number_of_inquiries 

然而,問題是,我的WHERE子句攪亂查詢,因爲我查詢同一張桌子。這裏是代碼:

SELECT owner_id, 
Count(*) AS number_of_cancelled_bookings 
FROM bookings 
WHERE state IN ('cancelled') 
GROUP BY owner_id 
ORDER BY 1; 

很容易單獨檢索列,但我希望所有這些。假設我想要number_of_concluded_bookings以及那將意味着我將不得不改變WHERE子句...

幫助非常感謝!

+0

你能提供從預訂表中的一些樣本數據? – supergrady

+1

您需要一個條件集合:'COUNT(CASE WHEN IN IN'('cancel')THEN 1 END''或'SUM(CASE WHEN IN INE''''''')然後在每個條件下重複此操作 – dnoeth

+0

這不夠好?https://gyazo.com/9d65a59eb26be135e6bf44b85ead15b7 – DBE7

回答

2

考慮有條件聚集:

SELECT owner_id, 
     SUM(CASE WHEN state='concluded' THEN 1 ELSE 0 END) AS number_of_concluded_bookings, 
     SUM(CASE WHEN state='cancelled' THEN 1 ELSE 0 END) AS number_of_cancelled_bookings, 
     SUM(CASE WHEN state='declined' THEN 1 ELSE 0 END) AS number_of_declined_bookings, 
     SUM(CASE WHEN state='inquiries' THEN 1 ELSE 0 END) AS number_of_inquiries 
FROM bookings 
GROUP BY owner_id 
+0

感謝的人!還有就是答案:) – DBE7

+0

快速問題!如果我需要添加多個狀態到一列,該怎麼辦?像這樣:'SUM(CASE WHEN state ='queries','expired'THEN 1 ELSE 0 END)AS number_of_inquiries' – DBE7

+0

好聽!在WHEN子句中使用'IN()'和'OR',甚至嵌套'CASE'語句。 – Parfait