0

I have a pole table that can have one to four streetlights on it. Each row has a pole ID and the type (a description) of streetlight. I need the ID's to be unique with a column for each of the possible streetlights. The type/description can anyone of 26 strings.

I have something like this:

ID   Description
----------------
1    S 400
1    M 200
1    HPS 1000
1    S 400
2    M 400
2    S 250
3    S 300

What I need:

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

The order the descriptions get populated in the description columns is not important, e.g. for ID = 1 the HPS 1000 value could be in description column 1, 2, 3, or 4. So, long as all values are present.

I tried to pivot it but I don't think that is the right tool.

select * from table t
pivot (
max(Description) for ID in (1, 2, 3))

Because there are ~3000 IDs I would end up with a table that is ~3001 rows wide...

I also looked at this Oracle SQL Cross Tab Query But it is not quite the same situation.

What is the right way to solve this problem?

GMB
  • 216,147
  • 25
  • 84
  • 135
fallingdog
  • 192
  • 1
  • 2
  • 17

1 Answers1

1

You can use row_number() and conditional aggregation:

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

This handles up to 4 descriptions per id. To handle more, you can just expand the select clause with more conditional max()s.

GMB
  • 216,147
  • 25
  • 84
  • 135