我有一个查询,该查询将创建报告(Excel电子表格),现在我需要在报告中添加两列:“ 2017 DNR”和“ 2018 DNR”。表中有一列名为DNRDATE(格式为dd-MON-yy),如果为NULL,则在报告中我都需要两列都说“ NO”。如果有DNRDATE,则需要检查该日期是2017年还是2018年。如果是2017年,则两列都将为“ YES”。如果是2018,则“ 2017 DNR”得到“否”,而2018得到“是”。
我应该为此使用CASE WHEN吗?那怎么办?
答案 0 :(得分:1)
SELECT CASE WHEN to_char(dnrdate,'YYYY') = '2017' THEN 'YES' ELSE 'NO' END "2017 DNR",
CASE WHEN to_char(dnrdate,'YYYY') = '2018' THEN 'YES' ELSE 'NO' END "2018 DNR"
FROM ...
不要担心NULL
值的特殊逻辑。如果为DNRDATE IS NULL
,则这两个表达式都将返回“ NO”。
完整示例:
WITH test_data (dnrdate) AS (
SELECT to_date('05-JUN-2017','DD-MON-YYYY') FROM DUAL UNION ALL
SELECT to_date('05-JUN-2018','DD-MON-YYYY') FROM DUAL UNION ALL
SELECT NULL FROM DUAL )
SELECT dnrdate,
CASE WHEN to_char(dnrdate,'YYYY') = '2017' THEN 'YES' ELSE 'NO' END "2017 DNR",
CASE WHEN to_char(dnrdate,'YYYY') = '2018' THEN 'YES' ELSE 'NO' END "2018 DNR"
FROM test_data
+-----------+----------+----------+ | DNRDATE | 2017 DNR | 2018 DNR | +-----------+----------+----------+ | 05-JUN-17 | YES | NO | | 05-JUN-18 | NO | YES | | | NO | NO | +-----------+----------+----------+