SQL CASE条件始终返回ELSE值

时间:2016-03-08 10:10:36

标签: sql sqlite case

我有一个迷你数据库(mymoney),其中有一个名为total_amount的列。现在,我想根据{{1}中的行值获取此列并广告额外的列GRP2(值为lowmediumhigh) }列。 所以我有这个

total_amount

我想这个

total_amount
5000
27000
36000
50000

我尝试使用以下SQL查询:

total_amount    GRP2
5000            low
27000           low
36000           medium
50000           high

但是在SELECT mymoney.total_amount, CASE mymoney.total_amount WHEN mymoney.total_amount <= 30000 THEN 'low' WHEN mymoney.total_amount >= 31000 AND mymoney.total_amount <= 40000 THEN 'medium' ELSE 'high' END AS GRP2 FROM mymoney 中,我到处都有GRP2,即使high中有明显的数字应该标记为total_amountlow。 (顺便说一句:medium中值的数据类型都是整数)。

total_amount

有谁能告诉我我做错了什么?

3 个答案:

答案 0 :(得分:1)

您滥用CASE表达式。试试这样:

SELECT total_amount,
    CASE 
        WHEN total_amount <= 30000 THEN 'low'
        WHEN total_amount > 30000 AND total_amount <= 40000 THEN 'medium'
        ELSE 'high'
    END AS GRP2
FROM gates_money

答案 1 :(得分:1)

您使用简单的CASE表达式,而您需要搜索CASE表达式

SELECT mymoney.total_amount,
    CASE 
        WHEN mymoney.total_amount <= 30000 THEN 'low'
        WHEN mymoney.total_amount >= 31000 AND mymoney.total_amount <= 40000 THEN 'medium'
        ELSE 'high'
    END AS GRP2
FROM mymoney

答案 2 :(得分:0)

你也可以试试这个:

SELECT mymoney.total_amount, 
GRP2 = CASE 
        WHEN mymoney.total_amount <= 30000 THEN 'low'
        WHEN mymoney.total_amount >= 31000 AND mymoney.total_amount <= 40000  THEN 'medium'
        ELSE 'high'
       END 
FROM gates_money

MSDN Documentation

此致