在 Oracle 中使用 Pivot 将行转置为列

Transpose rows into columns using Pivot in Oracle

我有一个 select 查询 returns 结果如下。

我想更新查询以将行转置为列,使其看起来像输出 table --

我试过使用 Pivot,但它不起作用。感谢任何帮助。谢谢

我得到了所需的输出。但是,如果同一 ID 和字段名有多个值,如何获取所有这些值。 i/p 和 o/p 示例如下。

I/P:

O/P:

使用 pivot 你可以做:

select *
from your_table
pivot (
  max(coalesce(text, to_char(num)))
  for (fieldname) in ('Width' as width, 'Height' as height, 'Comments' as comments))
ID   WIDTH HEIGHT COMMENTS
---- ----- ------ ---------
1051 121   2      FP-SK/124
1170 5678  5

我使用了 max(coalesce(text, to_char(num))),因为您需要将两列有效地塞进一列,并且您需要 to_char(),因为它们是不同的数据类型。如果一行在两列中都有一个值,那么您最终得到的值可能不是您想要的,但是您需要定义在这种情况下应该发生什么。

您也可以使用条件聚合,这正是 pivot 在幕后所做的;这里简化为不合并,假设您不会填充两列:

select id,
  max(case when fieldname = 'Width' then text end) as width,
  max(case when fieldname = 'Height' then num end) as height,
  max(case when fieldname = 'Comments' then text end) as comments
from your_table
group by id
ID   WIDTH HEIGHT COMMENTS
---- ----- ------ ---------
1051 121        2 FP-SK/124
1170 5678       5

db<>fiddle

注意 height 值现在是一个数字;在枢轴版本中,它是——而且必须是——一个字符串。您当然可以将结果转换为不同的数据类型。

How do we get multiple values in the output separated by commas

您可以从 max() 更改为 listagg():

select *
from your_table
pivot (
  listagg(coalesce(text, to_char(num)), ',')
  for (fieldname) in ('Width' as width, 'Height' as height, 'Comments' as comments))

select id,
  listagg(case when fieldname = 'Width' then text end, ',') within group (order by text) as width,
  listagg(case when fieldname = 'Height' then num end, ',') within group (order by text) as height,
  listagg(case when fieldname = 'Comments' then text end, ',') within group (order by text) as comments
from your_table
group by id

两者都得到

  ID WIDTH      HEIGHT     COMMENTS
---- ---------- ---------- ----------
1051 121,95                Sample
1170 5678       2,5

db<>fiddle