vertica检查两列中每个组的唯一元素是否相同

时间:2014-11-07 15:49:10

标签: sql comparison unique vertica

vertica中的表:

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中实现这一点?

1 个答案:

答案 0 :(得分:2)

假设两列中的值对于给定的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;