根据日期将报告列设置为是或否 - Oracle SQL

Setting report column to YES or NO based on date - Oracle SQL

我有一个将创建报告(Excel 电子表格)的查询,现在我需要向报告添加两列:“2017 DNR”和“2018 DNR”。 table 中有一列名为 DNRDATE(格式为 dd-MON-yy),如果它为 NULL,我需要两列都在报告中显示 "NO"。如果有 DNRDATE,需要检查该日期是 2017 年还是 2018 年。如果是 2017 年,那么两列都会得到 "YES"。如果是 2018 年,则“2017 DNR”获得 "NO",2018 年获得 "YES."

我应该为此使用 CASE WHEN 吗?那将如何运作?

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,那么这两个表达式都将 return "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       |
+-----------+----------+----------+