在 SQL 中使用 Case 语句
Using Case Statement in SQL
我一直在学习 SQL,我正在尝试了解 Oracle Live 上的 CASESQL:
这是我正在尝试使用的查询:
SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;
这个查询给我的输出为:
ORA-00923: FROM keyword not found where expected
谁能解释一下哪里出了问题?
Oracle 数据库对象名称在转义时应出现在 双 引号内,而不是单引号内。单引号表示字符串文字,而不是别名。以下版本应该有效:
SELECT FIRST_NAME, LAST_NAME,
CASE WHEN SALARY > 10000 THEN 'Salary is greater than 10000'
WHEN SALARY < 10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS "SALARY STATEMENT"
FROM hr.employees;
你得到了完美的答案。但是在oracle中你也可以使用decode.
SELECT FIRST_NAME, LAST_NAME,
DECODE(SIGN(SALARY-10000),1, 'Salary is greater than 10000',-1, 'Salary is less than 10000', 'Salary is equal to 10000')
FROM hr.employees;
我一直在学习 SQL,我正在尝试了解 Oracle Live 上的 CASESQL:
这是我正在尝试使用的查询:
SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;
这个查询给我的输出为:
ORA-00923: FROM keyword not found where expected
谁能解释一下哪里出了问题?
Oracle 数据库对象名称在转义时应出现在 双 引号内,而不是单引号内。单引号表示字符串文字,而不是别名。以下版本应该有效:
SELECT FIRST_NAME, LAST_NAME,
CASE WHEN SALARY > 10000 THEN 'Salary is greater than 10000'
WHEN SALARY < 10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS "SALARY STATEMENT"
FROM hr.employees;
你得到了完美的答案。但是在oracle中你也可以使用decode.
SELECT FIRST_NAME, LAST_NAME,
DECODE(SIGN(SALARY-10000),1, 'Salary is greater than 10000',-1, 'Salary is less than 10000', 'Salary is equal to 10000')
FROM hr.employees;