我一直在搜索很多,在示例中,一切看起来都不错,但事实上并非如此。 我想根据金额来计算加薪幅度。显示缺少关键字错误。
SELECT o.operator_name,
o.salary,
(CASE o.salary
WHEN o.salary < 500 THEN o.salary * 1.35
WHEN o.salary >= 500 AND o.salary < 1000 THEN o.salary * 1.15
WHEN o.salary >= 1000 AND o.salary < 1500 THEN o.salary * 1.05
END) AS "Increase"
FROM operators o;
我尝试使用IF ELSIF,我得到“FROM不是预期的地方”。
答案 0 :(得分:3)
您混合了两种CASE
格式,请尝试:
SELECT o.operator_name,
o.salary,
CASE WHEN o.salary < 500 THEN o.salary * 1.35
WHEN o.salary >= 500 AND o.salary < 1000 THEN o.salary * 1.15
WHEN o.salary >= 1000 AND o.salary < 1500 THEN o.salary * 1.05
ELSE o.salary
END AS "Increase"
FROM operators o;
此格式允许使用多个/不同的字段以及比较运算符。如果您想要为1500及以上的工资值返回某些内容,您可能还需要在ELSE
之前END
。
值得注意的是,CASE
符合首次符合标准,因此您可以使用:
SELECT o.operator_name,
o.salary,
CASE WHEN o.salary < 500 THEN o.salary * 1.35
WHEN o.salary < 1000 THEN o.salary * 1.15
WHEN o.salary < 1500 THEN o.salary * 1.05
ELSE o.salary
END AS "Increase"
FROM operators o;
CASE
的其他格式对您的示例不起作用,但这是一个显示用法的简单示例:
SELECT CASE col1
WHEN 'cat' THEN 1
WHEN 'dog' THEN 2
END
FROM table1
这相当于:
SELECT CASE WHEN col1 = 'cat' THEN 1
WHEN col1 = 'dog' THEN 2
END
FROM table1
答案 1 :(得分:1)
看起来你想要ELSE:
SELECT o.operator_name,
o.salary,
(CASE
WHEN o.salary < 500 THEN o.salary * 1.35
WHEN o.salary >= 500 AND o.salary < 1000 THEN o.salary * 1.15
WHEN o.salary >= 1000 AND o.salary < 1500 THEN o.salary * 1.05
ELSE o.salary
END) AS "Increase"
FROM operators o;
答案 2 :(得分:0)
SELECT o.operator_name,
o.salary,
CASE
WHEN o.salary < 500 THEN o.salary * 1.35
WHEN o.salary >= 500
AND o.salary < 1000 THEN o.salary * 1.15
WHEN o.salary >= 1000
AND o.salary < 1500 THEN o.salary * 1.05
END AS "Increase"
FROM operators o;
应该做的伎俩!
答案 3 :(得分:0)
看起来你错过了默认情况。您必须使用'ELSE default_value'完成您的案例。所以:
CASE foo
WHEN bar THEN 1
WHEN baz THEN 2
ELSE 0
END