代码之家  ›  专栏  ›  技术社区  ›  John Thomas

如何在Snowflake(SQL)中添加指示重复id的列?

  •  1
  • John Thomas  · 技术社区  · 4 年前

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

    表1

     ID    data
    001  Walter
    002  Skylar
    003    Hank
    004   Marie
    

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

    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 = 1 和 ID = 3 table2_multiple = 1 ,因为它们在表2中出现了不止一次!

    2 回复  |  直到 4 年前
        1
  •  2
  •   eshirvana    4 年前

    尽管这是一件很奇怪的事情,但以下是你可以做到的:

    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
  •  0
  •   xQbert    4 年前

    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。distinct然后消除所有重复项。

    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)获取表2中的计数在这种情况下,子查询将只返回每个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