[英]MySQL 'where case' apply only to some value
我有下表:
id | date_inserted | type | route_id | route_type | km
1 2016-01-05 Transport null Normal null
2 2016-01-06 Transport null Normal 50
3 2016-01-07 Transport 1 Normal null
4 2016-04-02 Transport 2 Normal null
5 2016-05-03 Services null Normal 20
6 2016-06-21 Transport null Exceptional 35
我需要按月檢索總路線。 這是通過執行以下操作來完成的:
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
type IN ('Transport', 'Services')
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC
輸出類似於:
type | total | month
Transport 3 1
Transport 1 2
Services 1 5
Transport 1 6
而且效果很好。 但是,現在要求我僅在類型為Transport
時應用某些條件,這些條件如下:
route_id
不能為null或 route_type
必須為“ Exceptional
或 route_type
為“ Normal
”且km
不等於零 因此,根據這種情況,這是我嘗試的方法:
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
type IN ('Transport', 'Services') AND
(CASE WHEN type = 'Transport' THEN
route_id IS NOT NULL OR
route_type = 'Exceptional' OR
(route_type = 'Normal' AND km != 0)
END)
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC
但是我的輸出是:
type | total | month
Transport 2 1
Transport 1 2
Transport 1 6
Services
行丟失。
您需要添加一個else段來處理服務。 如果希望是,則允許正常處理,請使用1 = 1。
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
type IN ('Transport', 'Services') AND
(CASE WHEN type = 'Transport' THEN
route_id IS NOT NULL OR
route_type = 'Exceptional' OR
(route_type = 'Normal' AND km != 0)
ELSE
1 = 1
END)
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC
正如其他人所說,您需要在案例中添加一個ELSE
,否則當該行為“ Service”時,它將返回null且不顯示記錄。
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
type IN ('Transport', 'Services') AND
(CASE WHEN type = 'Transport' THEN
route_id IS NOT NULL OR
route_type = 'Exceptional' OR
(route_type = 'Normal' AND km != 0)
ELSE 1 = 1
END)
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC;
您可以使用的另一個版本(我更喜歡)是:
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
(type = 'Services' OR
(type = 'Transport' and
(route_id IS NOT NULL OR
route_type = 'Exceptional' OR
(route_type = 'Normal' AND km != 0)
)
)
)
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC;
如果route_type
只能是“ Normal
和“ Exceptional
,則可以更改條件:
SELECT type, COUNT(id) AS `total`, MONTH(date_inserted) AS `month`
FROM routes
WHERE YEAR(date_inserted) = '2016' AND
(type = 'Services' OR
(type = 'Transport' and
(route_id IS NOT NULL OR
route_type = 'Exceptional' OR
km != 0
)
)
)
GROUP BY type, `month`
ORDER BY date_inserted ASC, `total` DESC;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.