我在使用带条件的CASE语句时面临一个小问题。基本上这是我的代码:
SELECT m.codmagazzino as Magazzino, m.integratore, i.nomeintegratore,
m.scadenza, m.quantita,
CASE m.scadenza
when (m.scadenza <= curdate() + interval 1 month) then '50%'
when (m.scadenza >= curdate() + interval 1 month) AND (m.scadenza <=
curdate() + interval 2 month) then '30%'
when (m.scadenza >= curdate() + interval 2 month) AND (m.scadenza <=
curdate() + interval 3 month) then '10%'
END AS ScontoSuggerito
FROM magazzino m INNER JOIN integratori i on m.integratore =
i.codintegratore
order by scadenza
;
我希望它做的是检查到期日期(scadenza),并且越早过期,建议的折扣(ScontoSuggerito)就越大。问题是它给了我null,尽管有些行属于CASE语句中的条件。
Scadenza
2 3 Creatina Mono 2017-11-03 12
2 5 MaxPower 2017-11-07 6
2 9 ImpactWhey 2017-11-24 11
2 4 Omega 3 2017-11-30 5
1 1 IsoWhey 2018-02-17 10
答案 0 :(得分:1)
可能只是一个语法问题:使用case语句时有两种模式:你似乎试图同时使用两种模式;当只能使用一个时。
DOCS:https://dev.mysql.com/doc/refman/5.7/en/case.html
一种模式开始case variable when valueA then ResultA when valueB then ResultB end
另一个是Case when OptionalCompoundCondition(s) then ResultA when ConditionsB then ResultB End
前者将1值与1值进行比较;后者允许复合条件。
SELECT m.codmagazzino as Magazzino
, m.integratore
, i.nomeintegratore
, m.scadenza
, m.quantita
, CASE when (m.scadenza <= curdate() + interval 1 month) then '50%'
when (m.scadenza >= curdate() + interval 1 month) AND (m.scadenza <= curdate() + interval 2 month) then '30%'
when (m.scadenza >= curdate() + interval 2 month) AND (m.scadenza <= curdate() + interval 3 month) then '10%'
END AS ScontoSuggerito
FROM magazzino m
INNER JOIN integratori i
on m.integratore = i.codintegratore
order by scadenza;