SQL:根据另一个 table 设置条件值,具有 BETWEEN 日期标准

SQL: Set conditional value based on another table, with a BETWEEN date criteria

对 SQL 有点陌生,在网上搜索了一些但找不到答案。

SQL 数据库是 Snowflake 数据库,我认为它是 ANSI 数据库。

我有一个事实 table 如下所述。相同 Issue/UPC/Warehouse/Date 的组合是可能的,因为每当报告新问题时都会添加新记录。

排除列是我想要弄清楚的 - 它应该是 'Y' 如果 Issue/UPC/Warehouse 和日期的组合在排除 table 中,如下所示。

棘手的部分是数据是在个别日期级别的,但如果它在范围内,我想排除它。

所以在这里,只有 I-100/1234/China/5-5-2019 和 I-324/1349/NewYork/6-1-2019 应该被排除,因为它们匹配排除 table.

中的值和日期范围

我尝试了以下查询,但是 DATES BETWEEN 的 SELECT 返回了超过 1 条记录,并给我这个错误 Single-row subquery returns more than one row.

update "FactDetails" 
set "EXCLUDE" = 'Y'

where ("UPC","Warehouse", "Issue") in
    ("UPC","Warehouse", "Issue" from "Exclusions"
     where "PLANT_NUMBER" is not null
     and "ISSUE_CODE" is not null)

and "Date" between 
    (select "DATE_FROM" from "Exclusion"
     where "PLANT_NUMBER" is not null
     and "ISSUE_CODE" is not null) and
    (select "DATE_TO" from "Exclusion"
     where "PLANT_NUMBER" is not null
     and "ISSUE_CODE" is not null);

另一个复杂性是排除table可以有'levels'通过UPC/Issue/Warehouse的组合来排除。仓库是最具体的,如果只是 UPC,这涵盖了最多的数据。

如果我没理解错的话,你可以用exists:

update t
    set exclude = 'Y'
    where exists (select 1
                  from exclusions e
                  where e.issue_code = t.issue_code and
                        e.upc = t.upc and
                        e.warehouse = t.warehouse and
                        t.date between e.date_from and e.date_to
                 );