如何使用 join 和 row_number 更改 db2 中包含行的列?

How to change columns with rows in db2 using join and row_number?

我有一个table: city_name

需要这样获取: city_n1n2n3

我已经有了解决方案,但需要使用连接和 row_number():

select city, coalesce(max(case when id_name=1 then name end),'nobody') as name1, coalesce(max(case when id_name =2 then name end),'nobody') as name2, coalesce(max(case when id_name=3 then name end),'nobody') as name3 from city_name group by按城市 desc 排序的城市

提前致谢。

这是一个带有行号的解决方案,但它不是最佳解决方案,因为您事先不知道有多少用户(因此您可以拥有多少列)

with cityuserwithrow as (
select f1.*, rownumber() over(partition by f1.city order by f1.name) as rang
from city_name f1
)
select distinct f0.city, 
ifnull(f1.name, 'NOBODY') as NAME1, 
ifnull(f2.name, 'NOBODY') as NAME2, 
ifnull(f3.name, 'NOBODY') as NAME3
from city_name f0
left outer join cityuserwithrow f1 on (f0.city, 1)=(f1.city, f1.rang)
left outer join cityuserwithrow f2 on (f0.city, 2)=(f2.city, f2.rang)
left outer join cityuserwithrow f3 on (f0.city, 3)=(f3.city, f3.rang)