【问题标题】:Snowflake, SQL where clause雪花,SQL where 子句
【发布时间】:2021-04-05 12:09:37
【问题描述】:

我需要用 where 子句编写查询:

where       
    pl.ods_site_id in (select id from table1 where ...)

但是如果子查询 (table1) 没有返回任何内容,那么 where 子句不需要包含在结果查询中(就像它返回 TRUE 一样)。

我该怎么做? (我有雪花 SQL 方言)

【问题讨论】:

    标签: sql snowflake-cloud-data-platform


    【解决方案1】:

    您可以包含第二个条件:

    where pl.ods_site_id in (select id from table1 where ...) or
          not exists (select id from table1 where ...)
    

    这会显式检查不返回任何行的子查询。

    【讨论】:

      【解决方案2】:

      如果您愿意改用join,Snowflake 支持qualify 子句,这可能会派上用场。你可以在 Snowflake 上运行它来看看它是如何工作的。

      with 
      pl (ods_site_id) as  (select 1 union all select 5),
      
      table1 (id) as (select 5) --change this to 7 to test if it returns ALL on no match
      
      select a.*
      from pl a
      left join table1 b on a.ods_site_id = b.id -- and other conditions you want to add
      qualify b.id = a.ods_site_id --either match the join condition
              or count(b.id) over () = 0; --or make sure there is 0 match from table1
      

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 1970-01-01
        • 2021-12-23
        • 2021-10-05
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多