繁体   English   中英

列到行仅一列

[英]column to row for only one column

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

输出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

请尝试在下面的查询中查找第二个解决方案:

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

小提琴演示

另一种方法(适用于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)
  );

这是一个sqlfiddle演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM