这些是我在显示数据时必须使用的表
data1
和我们用来加入表格的查询
table1
-----------------------------------------------------
col1 col2 id
1223 ram 254
1232 rajesh 345
table 2
--------------------------------------
id col5 col6 col7 col8
254 1223-1 8789 abc 67
254 1223-2 8790 efg 87
254 1223-3 8791 bcd 67
254 1223-4 8792 abc 87
345 1232-1 7897 cdf 89
345 1232-2 7898 cdf 60
使用上述查询时的输出
select
t1.col1,
listagg(t2.col5,',') within group(order by t2.col6)as col5,
listagg(t2.col7,',') within group(order by t2.col6)as col7,
listagg(t2.col8,',') within group(order by t2.col6)as col8
from
table1 t1
join table2 t2 on t1.id=t2.id;
group by col1
预期结果:
col1 col5 col7 col8
----------------------------------------------------------------------
1233 1223-1,1223-2,1223-3,1223-4 abc,efg,bcd,abc 67,87,67,87
1232 1232-1,1232-2 cdf,cdf 89,60
我们不应该使用Wm_concat,因为它没有文档记录。 Col5,col7和Col8应仅按col6排序。
答案 0 :(得分:0)
这是一个解决方案,当按col6排序时,它返回所请求列的第一个不同事件。它使用一个中间步骤来首先消除重复项,然后执行最终的listagg:
with t3 as (
SELECT T1.COL1
, T2.COL6
, case row_number() over (partition by t1.col1, t2.col5 order by t1.col1)
when 1 then t2.col5 -- Output the first occurrance of Col5
else null
end COL5
, case row_number() over (partition by t1.col1, t2.col7 order by t1.col1)
when 1 then t2.col7 -- Output the first occurrance of Col7
else null
end COL7
, case row_number() over (partition by t1.col1, t2.col8 order by t1.col1)
when 1 then t2.col8 -- Output the first occurrance of Col8
else null
end COL8
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.ID = T2.ID
)
select t3.col1
, listagg(COL5,',') WITHIN GROUP (ORDER BY T3.COL6) COL5
, listagg(COL7,',') WITHIN GROUP (ORDER BY T3.COL6) COL7
, listagg(COL8,',') WITHIN GROUP (ORDER BY T3.COL6) COL8
from t3
group by col1;
结果:
COL1 COL5 COL7 COL8
------- --------------------------- ----------- -----
1223 1223-1,1223-2,1223-3,1223-4 ABC,EFG,BCD 67,87
1232 1232-1,1232-2 CDF 89,60