如何在 Oracle sql 中将行转换为按多列分组的列
How to convert rows to columns group by multiple columns in Oracle sql
我有一个 table 数据如下:
a | b | c | d
a | b | c | e
a | b | c | f
g | h | i | j
g | h | i | k
g | h | i | l
我要转换数据如下:
a | b | c | d | e | f
g | h | i | j | k | l
尝试如下。但是没用。
select col1, col2, col3,
rtrim(xmlagg(xmlelement(e, col4 || ',')).extract ('//text()'), ',') val
from TABLEA
group by col1, col2, col
你能帮我解决这个问题吗?
您可以使用 row_number()
枚举前三列中具有相同值的行,然后使用条件聚合进行透视。
假设列名为 c1
到 c4
:
select c1, c2, c3,
max(case when rn = 1 then c4 end) c41,
max(case when rn = 2 then c4 end) c42,
max(case when rn = 3 then c4 end) c43
from (
select t.*, row_number() over(partition by c1, c2, c3 order by c4) rn
from mytable t
) t
group by c1, c2, c3
我有一个 table 数据如下:
a | b | c | d
a | b | c | e
a | b | c | f
g | h | i | j
g | h | i | k
g | h | i | l
我要转换数据如下:
a | b | c | d | e | f
g | h | i | j | k | l
尝试如下。但是没用。
select col1, col2, col3,
rtrim(xmlagg(xmlelement(e, col4 || ',')).extract ('//text()'), ',') val
from TABLEA
group by col1, col2, col
你能帮我解决这个问题吗?
您可以使用 row_number()
枚举前三列中具有相同值的行,然后使用条件聚合进行透视。
假设列名为 c1
到 c4
:
select c1, c2, c3,
max(case when rn = 1 then c4 end) c41,
max(case when rn = 2 then c4 end) c42,
max(case when rn = 3 then c4 end) c43
from (
select t.*, row_number() over(partition by c1, c2, c3 order by c4) rn
from mytable t
) t
group by c1, c2, c3