如何加入两个sql查询的结果?

时间:2016-04-30 03:59:56

标签: sql oracle

我正在开展一个项目并需要一些帮助。为了很好地构建问题,我创建了样本数据和所需的结果格式。我有一个有三列的表。所有三行都可以有重复数据,但CodeA,CodeB,CodeC的组合是唯一的。我需要有一个Oracle SQL查询(不是存储过程),以便我可以在右侧以下列格式生成逗号分隔数据。逗号分隔行中的值必须是不同的。此外,字段1应按排序顺序排列。

enter image description here

我创建的查询在这里,但下面的问题只是这不是我 DISTINCT 值。例如,在输出集的第1行,我得到了 A1 B1,B1,B2,B3 C1,C1,C2,C2 这是我不想要的。有谁能够帮我?

SELECT CodeA As "Field 1",
 LISTAGG(CodeB, ',') WITHIN GROUP (ORDER BY CodeA) AS "Field 2",
 LISTAGG(CodeC, ',') WITHIN GROUP (ORDER BY CodeA) AS "Field 3"
FROM Table
GROUP BY CodeA
UNION
SELECT CodeB As "Field 1",
 LISTAGG(CodeA , ',') WITHIN GROUP (ORDER BY CodeB) AS "Field 2",
 LISTAGG(Code3, ',') WITHIN GROUP (ORDER BY CodeB) AS "Field 3"
FROM Table
GROUP BY CodeB;

1 个答案:

答案 0 :(得分:0)

尝试:

select x.codea, x.codeb, y.codec
from
(
  select codea, listagg(codeb,',') within group (order by codeb) as codeb
  from (select distinct codea, codeb from tbl)
  group by codea
) x
join
(
  select codea, listagg(codec,',') within group (order by codec) as codec
  from (select distinct codea, codec from tbl)
  group by codea
) y
  on x.codea = y.codea