【问题标题】:vertica check if unique elements for each group from two columns are identicalvertica检查两列中每个组的唯一元素是否相同
【发布时间】:2014-11-07 15:49:10
【问题描述】:

垂直表格:

gid          a       b    
1            2       2    
1            3       2    
1            1       1    
2            2       1    
2            1       2
2            1       1    
3            1       1    
3            2       1

注意,对于给定的 gid,两列中的值是不同的(参见 gid=2) 对于每个 gid,我想检查 col a 中的唯一元素是否与 col b 中的唯一元素相同,如果相等,则 status = 1 else 0。预期结果是:

gid     status

1        0    
2        1
3        0

在vertica或sql中如何实现?

【问题讨论】:

    标签: sql comparison unique vertica


    【解决方案1】:

    假设对于给定的gid,两列中的值是不同的,您可以使用full outer joingroup by 来做到这一点:

    select coalesce(t.gid, t2.gid) as gid,
           (case when count(t.gid) = count(*) and count(t2.gid) = count(*)
                 then 1
                 else 0
            end)
    from invertica t full outer join
         invertica t2
         on t.gid = t2.gid and t.a = t2.b
    group by coalesce(t.gid, t2.gid);
    

    如果值不是不同的,您需要澄清您的问题以指定每列中的计数是否需要相同。 (如果您不关心计数,上述方法将起作用。)

    编辑:

    您也可以使用not exists 来表达这一点:

    select t.gid, max(val)
    from (select t.gid,
                 (case when not exists (select 1 from invertica t2 where t.gid = t2.gid and t.a = t2.b)
                       then 0
                       when not exists (select 1 from invertica t2 where t.gid = t2.gid and t.b = t2.a)
                       then 0
                       else 1
                  end) as val
          from invertica t
         ) t
    group by t.gid;
    

    【讨论】:

    • 对于给定的gid,两列中的值并不不同,我将更新OP
    • @tonystarkix 。 . .这很明显,实际上,一旦我多看一点数据。如果您关心 sets 值,这两种解决方案都有效。如果您关心计数,则需要做更多的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2017-05-03
    • 2013-05-02
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多