3

我有一张包含以下数据的表格

情况1:

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

X现在你看到 X 对所有的 id 都是通用的,所以在这种情况下我需要返回

案例2:

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

在这种情况下,X 和 Y 都是通用的,那么我需要返回 X 和 Y 逗号分隔 (X,y)

案例3

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

如果任何记录出现空值,我需要返回空值

实际上,我给你的数据是从 3 个表中填充的,所以我已经为此编写了查询,但是现在我需要比较组中的公共数据,这让我很困惑,如何比较团体?

注意:这里的组是基于ID

任何帮助都会得到帮助

4

1 回答 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 

(而不是 4,NULL)并且在这种情况下还希望返回 NULL 而不是分隔列表,那么您可以添加一个检查(上面的 4,NULL 即使在以前的 SQL 版本上也会返回 null,因为计数会'nt捆绑):

       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';
于 2013-01-24T13:33:26.177 回答