在组内比较以获取共同值

3
我有一张表格,其中包含以下数据
案例1:
table1
-------------
id      type
-------------
1         X
1         Y
2         X
3         Z
3         X
-------------

现在你看到X是所有id共有的,因此我需要在这种情况下返回X

情况2:

table1
-------------
id      type
-------------
1         X
1         Y
2         X
2         Y
3         X
3         Y
--------------

在这种情况下,X和Y都是通用的,我需要返回以逗号分隔的X和Y(X,y)。
第三种情况
table1
-------------
id      type
-------------
1         X
1         Y
2         X
2         Y
3         X
3         Y
4         NULL
------------------

如果任何一条记录为null,我需要返回NULL。
实际上,我展示给你的数据是从3个表中填充出来的,所以我已经编写了查询语句,但现在我需要比较组内公共数据的组,这让我感到困惑,如何比较这些组?
注意:这里的组是基于ID的。
任何帮助将不胜感激。
1个回答

1
你可以将出现次数与ID计数进行比较吗?
with data as (select rownum id, 'X' type from dual connect by level <= 3
              union all
              select rownum id, 'Y' type from dual connect by level <= 3
              union all
              select 3 id, 'Z' type from dual)
select wm_concat(distinct type)
  from (select type, count(*) over (partition by type) cnt, count(distinct id) over () total_ids
          from data)
 where cnt = total_ids;

在11g中,当然可以使用LISTAGG替代WM_CONCAT。如果每个id都有相同的type出现多次,则可以将count(*) over (partition by type)更改为count(distinct id) over (partition by type)
编辑:
如果您有
3, Z
3, NULL 

如果你想在这种情况下返回一个NULL而不是一个分隔列表,可以添加一个检查(与上面的4、NULL一起使用,即使在之前的SQL版本中也会返回null,因为计数不会匹配):

(而不是4,NULL)并且还想返回一个NULL而不是一个分隔列表,那么可以添加一个检查(在上面的4,NULL中,即使在先前的SQL版本中,它也会返回一个空值,因为计数不会匹配):

       with data as (select rownum id, 'X' type from dual connect by level <= 3
                      union all
                      select rownum id, 'Y' type from dual connect by level <= 3
                      union all
                      select 3 id, 'Z' type from dual)
        select wm_concat(distinct type)
          from (select type, count(*) over (partition by type) cnt, count(distinct id) over 

() total_ids,
                       max(case when type is null then 'Y' else 'N' end) over () has_null_in_set
                  from data)
         where cnt = total_ids
          and has_null_in_set = 'N';

不,你的编辑部分并不是我的一个有效案例,但非常感谢你提供的出色答案,我真的很感激。 - Gaurav Soni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接