SQL。根据另一个表设置条件值,并设置BETWEEN日期标准。

问题描述 投票:0回答:1

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

SQL数据库是一个Snowflake DB,我相信这是一个ANSI db。

我有一个事实表,如下所示。由于每当有新的问题被报告时,就会有一条新的记录被添加,所以相同的IssueUPCWarehouseDate的组合是可能的。

enter image description here

我想弄清楚的是排除列--如果IssueUPCWarehouse和Date的组合在排除表中,它应该是'Y',如下图所示。enter image description here

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

所以在这里,只有I-1001234China5-5-2019和I-3241349NewYork6-1-2019应该被排除,因为它们符合排除表中的值和日期范围。

我尝试了下面的查询,但是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);

另一个复杂的问题是,排除表可以有 "级别",通过UPCIssueWarehouse的组合来排除。仓库是最特殊的,如果只是UPC,这样覆盖的数据最多。enter image description here

sql conditional-statements snowflake-cloud-data-platform between ansi
1个回答
1
投票

如果我的理解正确,你可以使用 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
                 );
© www.soinside.com 2019 - 2024. All rights reserved.