我正在尝试根据从DB2
中的先前CASE条件获得的结果来过滤数据:
以下是用于过滤数据的初始查询:
SELECT EM.NAME,EM.ID,EM.DIV
CASE DEPT
WHEN '1' THEN 'FIN'
WHEN '2' THEN 'MKT'
WHEN '3' THEN 'IT'
WHEN '4' THEN 'HR' END AS DEPT_DESC
FROM EMPLOYEE_RCD EM;
样本数据:
NAME ID DIV DEPT_DESC
MICHAEL 3334 3 IT
SAMUEL 100922 1 FIN
ORINDA 7363 1 FIN
SARA 8383 2 MKT
RACHAEL 8383 4 HR
MARTIN 33312
SUZY 993 NA NA
MIKE 576 NULL NULL
我尝试过滤的结果:
SELECT EM.NAME,EM.ID,EM.DIV
CASE DEPT
WHEN '1' THEN 'FIN'
WHEN '2' THEN 'MKT'
WHEN '3' THEN 'IT'
WHEN '4' THEN 'HR' END AS DEPT_DESC
CASE DEPT_DESC
WHEN DEPT_DESC == '' THEN 'No Dept'
WHEN DEPT_DESC == NA THEN 'No Dept'
WHEN DEPT_DESC == NULL THEN 'No Dept'
FROM EMPLOYEE_RCD EM;
但没有得到结果而是得到了错误:
[Code: -104, SQL State: 42601] An unexpected token "== ''" was found following "WHEN DEPT_DESC". Expected tokens may include: "<space>".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.22.29
任何帮助,如何过滤数据并获得以下结果:
预期0 / P:
NAME ID DIV DEPT_DESC
MARTIN 33312
SUZY 993 NA NA
MIKE 576 NULL NULL
答案 0 :(得分:2)
您以错误的方式使用CASE
:
WHEN
子句后都需要一个[boolean]条件。 =
来实现相等,而不是使用双等号==
。您的查询应该类似于:
select name, id, div,
CASE
WHEN DEPT_DESC = '' THEN 'No Dept'
WHEN DEPT_DESC = NA THEN 'No Dept'
WHEN DEPT_DESC = NULL THEN 'No Dept'
END as dept_desc
from ( -- subquery runs first
SELECT EM.NAME,EM.ID,EM.DIV
CASE
WHEN DIV = '1' THEN 'FIN'
WHEN DIV = '2' THEN 'MKT'
WHEN DIV = '3' THEN 'IT'
WHEN DIV = '4' THEN 'HR' END AS DEPT_DESC
FROM EMPLOYEE_RCD EM
) x
;
答案 1 :(得分:2)
在给出的示例中,您只需要一个case语句
SELECT EM.NAME
, EM.ID
, EM.DIV
, CASE DEPT
WHEN '1' THEN 'FIN'
WHEN '2' THEN 'MKT'
WHEN '3' THEN 'IT'
WHEN '4' THEN 'HR'
ELSE 'No Dept' END AS DEPT_DESC
FROM
EMPLOYEE_RCD EM
顺便说一句,如果使用的SQL编辑器可以在编写SQL时对其进行解析(例如,免费的IBM Data Studio),则更容易发现和修复语法错误。