匹配日期以报告审查时间表

Matching dates to report review schedules

我有一个 table,其中列出了事件、事件的报告日期以及审查事件的日期,例如

ID | REPORT_DATE | RFD
1  | 2021-02-01  | 1st,15th
2  | 2021-02-16  | Tuesday
3  | 2021-02-14  | 4th,1st,8th,15th,23rd
4  | 2021-02-01  | 1st
5  | 2021-02-28  | 1st, Last

我开发了一个提取第 2 行和第 4 行的查询(请参阅下面的查询),但未能在逗号分隔值中找到匹配值。

select EVENT_ID, REPORT_DATE, RFD
from DB
where (lower(RFD) = lower(trim(to_char(REPORT_DATE, 'Day'))) or RFD like trim(to_char(REPORT_DATE, 'fmddth')) and RFD is not NULL)

我没有找到任何可以暗示如何解决此问题的在线讨论。我正在考虑将逗号分隔值转换为数组并在其中进行搜索,但我想知道是否有更简单的解决方案?

*说明: 我正在尝试提取报告日期(及其特征匹配)的所有记录;所以它应该提取日期和 RFD 包含匹配的星期几的事件,在一个月的第一天或一个月的最后一天(ids:1、2、4、5)。

如果无法规范化数据,则可以选择将 CSV 值即时转换为多行。您还可以使用正则表达式模式,例如:

select EVENT_ID, REPORT_DATE, RFD
from DB
where regexp_like(lower(RFD), '(^| |,)' || to_char(REPORT_DATE, 'fmday') || '(,| |$)')
or regexp_like(lower(RFD), '(^| |,)' || to_char(REPORT_DATE, 'fmddth') || '(,| |$)')
or (regexp_like(lower(RFD), '(^| |,)last(,| |$)') and REPORT_DATE = last_day(REPORT_DATE));

 EVENT_ID | REPORT_DATE | RFD      
 -------: | :---------- | :--------
        1 | 2021-02-01  | 1st,15th 
        2 | 2021-02-16  | Tuesday  
        4 | 2021-02-01  | 1st      
        5 | 2021-02-28  | 1st, Last

db<>fiddle

不过,如果您有大量数据要处理,性能可能是个问题。

如果您想将 CSV 字符串拆分成行,有多种方法,包括再次使用正则表达式:

select EVENT_ID, REPORT_DATE, regexp_substr(RFD, '(.*?)(,|$)', 1, level, NULL, 1) as RFD
from DB
connect by EVENT_ID = prior EVENT_ID
and level <= regexp_count(RFD, ',') + 1
and prior dbms_random.value is not null

或使用递归 CTE 和 simpler/faster 字符串函数:

with rcte (EVENT_ID, REPORT_DATE, VALUE, RFD) AS (
  select EVENT_ID, REPORT_DATE,
    lower(trim(case when instr(RFD, ',') > 0 then substr(RFD, 1, instr(RFD, ',') - 1) else RFD end)),
    lower(trim(case when instr(RFD, ',') > 0 then substr(RFD, instr(RFD, ',') + 1) end))
  from DB
  where RFD is not null
  union all
  select EVENT_ID, REPORT_DATE,
    trim(case when instr(RFD, ',') > 0 then substr(RFD, 1, instr(RFD, ',') - 1) else RFD end),
    trim(case when instr(RFD, ',') > 0 then substr(RFD, instr(RFD, ',') + 1) end)
  from rcte
  where RFD is not null
)
...

然后您可以检查各个行:

...
select EVENT_ID, REPORT_DATE, VALUE
from rcte
where VALUE = to_char(REPORT_DATE, 'fmday')
or VALUE = to_char(REPORT_DATE, 'fmddth')
or (VALUE = 'last' and REPORT_DATE = last_day(REPORT_DATE))

db<>fiddle

您可能会通过这种方法获得多次匹配 - 例如,如果您的第二个 ID 具有 RFD Tuesday, 16th - 您可能想要,或者可能需要抑制。

在速度和内存使用之间始终存在权衡取舍,因此探索多种解决方案可能是个好主意。

感谢 Alex Poole 能够用他们的查询回答我的问题,我相信他们最近更新了,但下面是适合我的情况的查询。使用的数据集包含 350 万条记录 x 12 个字段,并在不到 0.5 秒的时间内完成。下面是使用 Alex 代码的查询的一部分。

select EVENT_ID, REPORT_DATE, RFD
from DB
where (regexp_like(lower(RFD), '(^| |,)' || to_char(REPORT_DATE, 'fmday') || '(,| |$)') 
    or regexp_like(lower(RFD), '(^| |,)' || to_char(REPORT_DATE, 'fmddth') || '(,| |$)')
    or (regexp(lower(RFD), '(^| |,)last(,| |$)' and REPORT_DATE = last_day(REPORT_DATE)) 
    or RFD is NULL)
)