我下面的表格有: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