我的表格中只有一列具有所有不同的值,我需要将其分组成3对,3行中的3列请帮助
来源
COL1
-----
A
B
C
D
E
F
必需输出1:
COL1
------
A,B,C
D,E,F
必需的输出2:
col1 col2 col3
---- ---- ----
A B C
D E F
答案 0 :(得分:1)
输出1:
select listagg(col1, ',') within group (order by col1) as col
from (
select col1,
case
when row_number() over (order by col1) <= (count(*) over ()) / 2 then 0
else 1
end as grp
from foo
)
group by grp
order by grp;
对于输出2:
select max(col1) as col1,
max(col2) as col2,
max(col3) as col3
from (
select case mod(row_number() over (order by col1),3)
when 1 then col1
else null
end as col1,
case mod(row_number() over (order by col1),3)
when 2 then col1
else null
end as col2,
case mod(row_number() over (order by col1),3)
when 0 then col1
else null
end as col3,
case
when row_number() over (order by col1) <= (count(*) over ()) / 2 then 0
else 1
end as grp
from foo
)
group by grp
order by grp;
SQLFiddle示例:http://sqlfiddle.com/#!4/d699c/1
答案 1 :(得分:1)
请尝试以下查询第二个解决方案:
select Col1, Col2, Col3 From(
select
ceil(row_number() over(order by Col1)/3) Rnum,
mod(row_number() over(order by Col1)+2, 3)+1 Row_Num,
COl1
from
YourTable
)x pivot (min(Col1) for Row_Num in ('1' as Col1, '2' as Col2, '3' as Col3));
答案 2 :(得分:0)
另一种方式(将适用于3个记录的每个倍数)
OUTPUT1
select listagg(col1, ',') within group (order by col1) col1
from
(select col1, row_number() over(order by col1) rn
from t) tt
group by rn - decode(mod (rn, 3) ,0,3,mod (rn, 3));
OUTPUT2
select c2_col col1, c3_col col2, c1_col col3
from
(select rn - decode(mod (rn, 3) ,0,3,mod (rn, 3)) grp, mod(rn, 3) rnm, col1
from
(select col1, row_number() over(order by col1) rn
from t)) tt
pivot
(
max(col1) as col
for rnm in (0 as c1,1 c2,2 c3)
);