我有一张像
这样的表格colA colB colC
A 10 1
A 20 2
A 30 3
B 10 1
B 20 2
我想要一个像这样的输出
ColA colB colC
A 60 1,2,3
B 30 1,2
有人可以告诉我如何使用和不使用函数,以及在PL / SQL中吗?
答案 0 :(得分:1)
这是你需要的sql。 注意:它只能在oracle 11g R2上运行。
with tab as(
select 'A' col1,10 col2,1 col3 from dual union all
select 'A' col1,20 col2,2 col3 from dual union all
select 'A' col1,30 col2,3 col3 from dual union all
select 'B' col1,10 col2,1 col3 from dual union all
select 'B' col1,20 col2,2 col3 from dual )
select col1, sum(col2),listagg(col3,',') WITHIN GROUP (ORDER BY col3) AS col3_list
from tab group by col1
答案 1 :(得分:0)
假设您的表名是标签
with tab1(col1, col2) as (
select colA, sum(colB)
from tab group by colA
),
tab2(col1, col2) as (
select colA, LISTAGG(TO_CHAR(colC),',')
WITHIN GROUP (ORDER BY colC)
from tab group by colA
)
select a.col1, a.col2, b.col2
from tab1 a, tab2 b
where a.col1 = b.col1
输出:
COL1 COL2 COL2
A 60 1,2,3
B 30 1,2
有关LISTAGG
link
此link解释了multiple with clause
或者简单地说;
select colA, sum(colB) colB,LISTAGG(TO_CHAR(colC),',')
WITHIN GROUP (ORDER BY colC)
from tab group by colA
答案 2 :(得分:0)
Probably this may the easiest solution syntactically :)
SELECT COLA,
SUM(COLB),
WMSYS.WM_CONCAT(COLC)
FROM
(SELECT 'A' cola,10 AS colb,1 AS colc FROM dual
UNION
SELECT 'A' cola,20 AS colb,2 AS colc FROM dual
UNION
SELECT 'A' cola,30 AS colb,3 AS colc FROM dual
UNION
SELECT 'B' cola,10 AS colb,1 AS colc FROM dual
UNION
SELECT 'B' cola,20 AS colb,2 AS colc FROM dual
)
GROUP BY COLA ;
COLA SUM(COLB)WMSYS.WM_CONCAT(COLC) A 60 1,2,3