我有一张能装一到四个路灯的电线桌。每一行都有一个杆ID和路灯的类型(描述)。我需要ID是唯一的,为每个可能的路灯列。类型/描述可以是26个字符串的任何人。
我有这样的事情:
ID Description
----------------
1 S 400
1 M 200
1 HPS 1000
1 S 400
2 M 400
2 S 250
3 S 300我需要的是:
ID Description_1 Description_2 Description_3 Description_4
------------------------------------------------------------------
1 S 400 M 200 HPS 1000 S 400
2 M 400 S 250
3 S 300在描述列中填充描述的顺序并不重要,例如,对于ID = 1,HPS 1000值可能在描述列1、2、3或4中。所以,只要所有的值都存在。
我试着转动它,但我不认为这是正确的工具。
select * from table t
pivot (
max(Description) for ID in (1, 2, 3))因为有大约3000个I,我最终会得到一个3001行宽的表.
我也看过这个Oracle SQL Cross Tab Query,但情况不完全一样。
解决这个问题的正确方法是什么?
发布于 2020-06-25 19:44:14
您可以使用row_number()和条件聚合:
select
id,
max(case when rn = 1 then description end) description_1,
max(case when rn = 2 then description end) description_2,
max(case when rn = 3 then description end) description_3,
max(case when rn = 4 then description end) description_4
from (
select t.*, row_number() over(partition by id order by description) rn
from mytable t
) t
group by id这将处理每个id最多4种描述。要处理更多问题,只需使用更多的条件select s展开max()子句即可。
https://stackoverflow.com/questions/62583061
复制相似问题