SQLite CASE WHEN with >= evaluation

时间:2019-04-08 13:51:25

标签: sqlite case-when

I am writing a script that will calculate a score for a board game called Agricola. The following query works:

SELECT
CASE $Fields WHEN 0 THEN -1
             WHEN 1 THEN -1
             WHEN 2 THEN 1
             WHEN 3 THEN 2
             WHEN 4 THEN 3             
END
;

The following query will NOT work:

SELECT
CASE $Fields WHEN 0 THEN -1
             WHEN 1 THEN -1
             WHEN 2 THEN 1
             WHEN 3 THEN 2
             WHEN 4 THEN 3
             WHEN >= 5 THEN 4
END
;

All that I get is a message essentially saying "error near '>=': syntax error". How can I represent this WHEN >= 5 block inside of this CASE statement?

2 个答案:

答案 0 :(得分:2)

If you use the alternative form of the CASE expression, you may use inequalities:

SELECT
    CASE WHEN $Fields = 0 THEN -1
         WHEN $Fields = 1 THEN -1
         WHEN $Fields = 2 THEN 1
         WHEN $Fields = 3 THEN 2
         WHEN $Fields = 4 THEN 3
         WHEN $Fields >= 5 THEN 4
    END;

If you want to keep using your form of CASE, one option here would be to bucket the $Fields >= 5 case into the ELSE condition. This would assume that $Fields would never be negative. Assuming this, you could try:

SELECT
    CASE $Fields WHEN 0 THEN -1
                 WHEN 1 THEN -1
                 WHEN 2 THEN 1
                 WHEN 3 THEN 2
                 WHEN 4 THEN 3
                 ELSE 4
    END;

答案 1 :(得分:1)

CASE x will only evaluate on single values, you need CASE WHEN x ..., like so:

SELECT CASE
         WHEN $Fields >= 5 THEN 4
         WHEN $Fields = 4 THEN 3
         -- so on
       END