I have a list of occupants of a property and need to manipulate the data so it instead shows the property as one row with each additional occupant appearing in a new column.
Here is what I've managed to do so far:
with RANKING AS
( Select
Postcode
, Number
, Occupant
, RANK() OVER
(Partition by Postcode order by Occupant) as [Rank]
from Reporting.dbo.Test --order by [Rank] desc
)
The query in RANKING outputs the following table:
Postcode | Number | Occupant | Rank
AA001AA | 12 | D | 1
AA001AA | 12 | E | 2
AA001AA | 12 | K | 3
AA001AA | 12 | M | 4
AA001AA | 12 | T | 5
BB001BB | 8 | M | 1
BB001BB | 8 | R | 2
etc.
I've then tried to use the value of ranking to create columns, like so:
Select distinct
i.Postcode
, i.Number
, case when i.[rank] = 1 then i.Occupant end as [First Tennant]
, case when i.[rank] = 2 then i.Occupant end as [Second Tennant]
, case when i.[rank] = 3 then i.Occupant end as [Third Tennant]
, case when i.[rank] = 4 then i.Occupant end as [Fourth Tennant]
, case when i.[rank] = 5 then i.Occupant end as [Fifth Tennant]
from Reporting.dbo.Test u
inner join RANKING i on i.Postcode = u.Postcode
Now, 2 questions:
1) Is there any way to automate this process so for a rank of x we have x tenant rows
2) The table this outputs is
Postcode | Number | First Tennant | Second Tennant | Third Tennant | Fourth Tennant | Fifth Tennant |
AA001AA | 12 | D | NULL | NULL | NULL | NULL |
AA001AA | 12 | NULL | E | NULL | NULL | NULL |
etc.
How do I condense this list so each postcode only has one row and all the non-null values appear on that row.