在 select SQL Oracle 中动态创建列

Dynamically create columns in select SQL Oracle

我想在一行中显示调查员姓名职务

如何将 title 列设置为 title1, title2, title 3,或者在 SQL Oracle 中动态地依此类推?

头衔的数量可能会有所不同,因此如果调查员有 4 个头衔,那么会有 4 列 title1title2 , title3, title4.

这是我当前的查询:

SELECT al.name, al.title_name FROM INVESTIGATOR a1

There is no max number for titles but by looking at the data I think I can set it to a fixed number

如果您可以选择最大数量的标题,那么您不需要动态执行此操作。

如果您对每个名称的每个标题应用排名,例如:

select name,
  title_name,
  dense_rank() over (partition by name order by title_name) as rnk
from investigator

按字母顺序排列,但如果您愿意,可以选择不同的顺序;然后你旋转那个查询的结果:

select *
from (
  select name,
    title_name,
    dense_rank() over (partition by name order by title_name) as rnk
  from investigator
)
pivot (
  max(title_name)
  for (rnk) in (
    1 as title1, 2 as title2, 3 as title3, 4 as title4
  )
)

我最多选择了四个标题,但您可以根据需要添加任意数量的标题。

how can I name my columns Title1, title2, title3...

我已经在枢轴的 in() 子句中使用别名完成了这项工作。

使用您提供输出的示例数据:

NAME TITLE1 TITLE2 TITLE3 TITLE4
---- ------ ------ ------ ------
Abu  AP     AR     AS
Cu   TA
Gyu  AP

如果您使用的不是 11g 或更高版本,那么您可以进行手动转换,这对 Oracle 在幕后所做的工作至关重要:

select name,
  max(case when rnk = 1 then title_name end) as title1,
  max(case when rnk = 2 then title_name end) as title2,
  max(case when rnk = 3 then title_name end) as title3,
  max(case when rnk = 4 then title_name end) as title4
from (
  select name,
    title_name,
    dense_rank() over (partition by name order by title_name) as rnk
  from investigator
)
group by name

得到相同的结果。

db<>fiddle