[英]SQL query to convert no. of rows to no. of column in oracle
I need to convert all rows into columns ie no.of columns= total no.我需要将所有行转换为列,即列数 = 总数。 of values in col2 and col3 related to col1.
col2 和 col3 中与 col1 相关的值。
Scenario设想
Query tried:查询尝试:
with cte as (
select 'A' as col1, 1 as col2, 2 as col3 from dual
union
select 'A' as col1, 3 as col2, 4 as col3 from dual
union
select 'A' as col1, 5 as col2, 6 as col3 from dual
union
select 'B' as col1, 10 as col2, 101 as col3 from dual
union
select 'B' as col1, 20 as col2, 202 as col3 from dual
union
select 'C' as col1, 50 as col2, 501 as col3 from dual
union
select 'C' as col1, 60 as col2, 601 as col3 from dual
union
select 'C' as col1, 70 as col2, 701 as col3 from dual
) select * from cte
How can I write a pivot query here?如何在此处编写数据透视查询?
One approach to handle this uses a pivot query along with ROW_NUMBER
:处理此问题的一种方法是使用数据透视查询和
ROW_NUMBER
:
WITH cte AS (
SELECT Col1, Col2, Col3,
ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col2) rn
FROM yourTable
)
SELECT
Col1,
MAX(CASE WHEN rn = 1 THEN Col2 END) AS Col2,
MAX(CASE WHEN rn = 1 THEN Col3 END) AS Col3,
MAX(CASE WHEN rn = 2 THEN Col2 END) AS Col4,
MAX(CASE WHEN rn = 2 THEN Col3 END) AS Col5,
MAX(CASE WHEN rn = 3 THEN Col2 END) AS Col6,
MAX(CASE WHEN rn = 3 THEN Col3 END) AS Col7
FROM cte
GROUP BY
Col1;
-- Oracle 11g+: pivot
with cte as (
select 'A' as col1, 1 as col2, 2 as col3 from dual union all
select 'A' as col1, 3 as col2, 4 as col3 from dual union all
select 'A' as col1, 5 as col2, 6 as col3 from dual union all
select 'B' as col1, 10 as col2, 101 as col3 from dual union all
select 'B' as col1, 20 as col2, 202 as col3 from dual union all
select 'C' as col1, 50 as col2, 501 as col3 from dual union all
select 'C' as col1, 60 as col2, 601 as col3 from dual union all
select 'C' as col1, 70 as col2, 701 as col3 from dual )
select *
from
(select t.*, row_number() over (partition by col1 order by col2) rn
from cte t
)
pivot (max(col2) as pc2, max(col3) as pc3 for rn in (1,2,3));
C 1_PC2 1_PC3 2_PC2 2_PC3 3_PC2 3_PC3
- ---------- ---------- ---------- ---------- ---------- ----------
A 1 2 3 4 5 6
B 10 101 20 202
C 50 501 60 601 70 701
use row_number()
and conditional aggregation使用
row_number()
和条件聚合
select col1,
max(case when rn=1 then col2 end) as col2,
max(case when rn=2 then col2 end) as col3,
max(case when rn=3 then col2 end) as col4,
max(case when rn=1 then col3 end) as col5,
max(case when rn=2 then col3 end) as col6,
max(case when rn=3 then col3 end) as col7
from
(
select *, row_number() over(partition by col1 order by null) as rn
from tablename
)A group by col1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.