ich die folgende Tabelle haben:MySQL ‚where Fall‘ nur
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
Und ich brauchte die gesamten Strecken nach Monaten abzurufen. Das war erreichen, indem Sie:
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
Der Ausgang ist so etwas wie:
type | total | month
Transport 3 1
Transport 1 2
Services 1 5
Transport 1 6
Und es funktioniert gut. Doch jetzt wurde ich gebeten, einige Bedingungen nur anzuwenden, wenn der Typ Transport
ist, die Bedingungen sind die folgenden:
- Die
route_id
darf nicht null sein OR - Die
route_type
mussExceptional
OR - Die
route_type
seinNormal
ist UNDkm
ist nicht gleich Null
So, nach diesen Bedingungen ist es das, was ich versucht habe:
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
Aber meine Ausgabe lautet:
type | total | month
Transport 2 1
Transport 1 2
Transport 1 6
Die Services
Reihe fehlt.
eine 'ELSE hinzufügen 'Bedingung für die' CASE'-Anweisung, die True zurückgibt ... z 'CASE WHEN <...> ELSE 1 = 1 END' – abigperson
Ihr Fall wird null für' Services' zurückgeben. Handle es in einem anderen 'When' oder' else' – GurV
@PJSantoro Warum posten Sie dies als Antwort? Die Analyse und die vorgeschlagene Lösung sind beide korrekt. – jpw