组查询中的 Oracle 数据透视列
Oracle Pivot Column in group query
我有以下工作查询:
WITH pivot_data AS (
select PSGROUP,
PSCOLUMN as PSCOLUMN
FROM LOG_PS_STATUS
)
SELECT *
FROM pivot_data
PIVOT (
MAX(NULL) --<-- pivot_clause
FOR PSCOLUMN--<-- pivot_for_clause
IN (&PS_COLUMNS.) --<-- pivot_in_clause
);
它显示了预期的结果:
值:
PSGroup PSColumn
A 1
A 2
A 3
B 1
B 2
B 3
C 3
结果如下:
PSGroup(Column vertically) PSColoumn(Horizontally)
1 2 3
A
B
C
现在我想将 PSGroup 列作为一组 PSColumn,输出应该如下所示:
A
1 2 3
B
1 2 3
C
3
您可以使用 listagg:
WITH pivot_data(PSGroup,PSColumn) AS (
select 'A', 1 FROM dual UNION all
select 'A', 2 FROM dual UNION all
select 'A', 3 FROM dual UNION all
select 'B', 1 FROM dual UNION all
select 'B', 2 FROM dual UNION all
select 'B', 3 FROM dual UNION all
select 'C', 3 FROM DUAL),
res(PSGroup,PSColumns) as(
SELECT PSGroup, LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)
FROM pivot_data
GROUP BY PSGroup)
select DECODE(PSColumns,NULL,PSGroup,NULL) AS PSGroup, PSColumns from(
select PSGroup, NULL as PSColumns from res
union all
select PSGroup, PSColumns from res)t
ORDER BY t.PSGroup, t.PSColumns NULLS first
另请注意,LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)
限制为 4000 个字符
我有以下工作查询:
WITH pivot_data AS (
select PSGROUP,
PSCOLUMN as PSCOLUMN
FROM LOG_PS_STATUS
)
SELECT *
FROM pivot_data
PIVOT (
MAX(NULL) --<-- pivot_clause
FOR PSCOLUMN--<-- pivot_for_clause
IN (&PS_COLUMNS.) --<-- pivot_in_clause
);
它显示了预期的结果:
值:
PSGroup PSColumn
A 1
A 2
A 3
B 1
B 2
B 3
C 3
结果如下:
PSGroup(Column vertically) PSColoumn(Horizontally)
1 2 3
A
B
C
现在我想将 PSGroup 列作为一组 PSColumn,输出应该如下所示:
A
1 2 3
B
1 2 3
C
3
您可以使用 listagg:
WITH pivot_data(PSGroup,PSColumn) AS (
select 'A', 1 FROM dual UNION all
select 'A', 2 FROM dual UNION all
select 'A', 3 FROM dual UNION all
select 'B', 1 FROM dual UNION all
select 'B', 2 FROM dual UNION all
select 'B', 3 FROM dual UNION all
select 'C', 3 FROM DUAL),
res(PSGroup,PSColumns) as(
SELECT PSGroup, LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)
FROM pivot_data
GROUP BY PSGroup)
select DECODE(PSColumns,NULL,PSGroup,NULL) AS PSGroup, PSColumns from(
select PSGroup, NULL as PSColumns from res
union all
select PSGroup, PSColumns from res)t
ORDER BY t.PSGroup, t.PSColumns NULLS first
另请注意,LISTAGG(PSColumn, ' ') WITHIN GROUP (order by PSColumn)
限制为 4000 个字符