我下面的表格有:MySQL的情況下,地方「只適用於一定的價值
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 '返回True的'CASE'語句的條件...例如'CASE WHERE <...> ELSE 1 = 1 END' – abigperson
您的情況下將返回「服務」爲空。在另一個'When'或'else'處理它 – GurV
@PJSantoro爲什麼不把它作爲答案?分析和提出的解決方案都是正確的。 – jpw