1

我的表中只有一列具有所有不同的值我需要将其分组为 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
4

3 回答 3

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

于 2013-09-30T06:54:23.627 回答
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));

小提琴演示

于 2013-09-30T07:25:26.437 回答
0

另一种方式(适用于每 3 条记录的倍数)

输出1

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));

输出2

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)
  );

这是一个 sqlfiddle 演示

于 2013-09-30T07:29:40.567 回答