【问题标题】:How to add a column indicating a repeat id in Snowflake (SQL)?如何在 Snowflake (SQL) 中添加指示重复 id 的列?
【发布时间】:2022-01-14 18:19:16
【问题描述】:

所以我有一个这样的表,其中每个 ID 每行都是唯一的:

table1

 ID    data
001  Walter
002  Skylar
003    Hank
004   Marie

我有另一个表,其中 ID 可以出现多次:

table2

ID  value
001     apple
001    banana
003     grape
004  graphite
003     jones
001      pear

我想要做的就是给这两个表,我想在表 1 中添加一列,以指示 一个 ID 是否在表 2 中出现多次

最终结果:

 ID    data  table2_multiple
001  Walter                1
002  Skylar                0
003    Hank                1
004   Marie                0  

这里我们显示ID = 1ID = 3 都有table2_multiple = 1,因为它们都在table2 中出现了不止一次!

【问题讨论】:

  • 你需要使用聚合函数和“group by”
  • 您对 SQL 很熟悉吗?如果是这样,您尝试过什么?如果不查看LEFT JOINgroup byHAVING
  • 可能使用表 2 的子查询将表 1 连接到聚合
  • 哦...也许您只想要一个计算列?

标签: sql join snowflake-cloud-data-platform


【解决方案1】:

尽管这样做很奇怪,但您可以这样做:

update table1
set table2_multiple = case when t.cnt > 1 then 1 else 0 end 
from (select ID , count(*) cnt from table2 group by ID) t 
where t.id = table1.id

或者如果您只想选择:

select t1.* , case when t2.cnt > 1 then 1 else 0 end as table2_multiple
from table1 t1 
join (select ID , count(*) cnt from table2 group by ID) t2
on t1.id = t2.id

【讨论】:

    【解决方案2】:

    在所有示例中,我们使用大小写表达式来确定计数是否 >1 设置为 1,否则为 0。

    基本聚合函数:

    SELECT t1.ID, t1.Data, case when count(*) > 1 then 1 else 0 end as table2_Multiple
    FROM Table1 t1 --t1 is an alias of table1
    LEFT JOIN table2 t2 --t2 is an alias of table2
     ON t1.ID = t2.ID
    GROUP BY T1.ID, T1.Data
    

    使用分析函数: (Count() over (partition xxx) 这基本上表示按唯一 T1ID 和数据计算所有记录,然后表达式表示如果该计数 > 1 返回 1,否则返回 0。然后,不同的会消除所有重复项。

    SELECT Distinct t1.ID
         , t1.Data
         , case when count() over (partition by T1.ID, T1.Data) > 1 then 1 else 0 end as Table_2_multiple
    LEFT JOIN Table2 T2
      on T1.ID = T2.ID
    

    在这种情况下,使用内联视图 (T2) 按 table2 获取计数,子查询将仅返回每个 ID 1 行,因此无需处理倍数。

    SELECT T1.*, case when coalesce(t2.ValueNo,0) > 1 then 1 else 0 end as table2_Multiple 
    FROM Table1
    LEFT JOIN (SELECT ID, count(*) as valueNo 
               FROM Table2 
               GROUP BY ID) T2
     on T1.ID = T2.ID
    

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 2022-12-02
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2021-03-25
      相关资源
      最近更新 更多