I have an existing table structure with sample data like
| Id | BookingId | Value | TypeId | AddedTime |
|---|---|---|---|---|
| 1 | 100 | 10 | T1 | 2021-03-22 08:51:52.6333333 |
| 2 | 100 | 20 | T2 | 2021-03-22 08:50:55.8133333 |
| 3 | 100 | 30 | T3 | 2021-03-22 08:50:22.1033333 |
| 4 | 200 | 50 | T1 | 2021-03-22 08:50:22.1033333 |
| 5 | 200 | 60 | T2 | 2021-03-22 08:50:22.1000000 |
| 6 | 200 | 70 | T3 | 2021-03-22 08:50:22.0800000 |
and now data model is changed and it becomes like
| Id | BookingId | Type1Value | Type2Value | Type3Value | AddedTime |
|---|
Please help me what would be query to copy data from previous table to new table.
Output should be something like
| Id | BookingId | Type1Value | Type2Value | Type3Value | AddedTime |
|---|---|---|---|---|---|
| 1 | 100 | 10 | 20 | 30 | |
| 2 | 200 | 50 | 60 | 70 |
I tried:
select BookingId
, Type1Value = max(case when RN=1 then Value else null end)
, Type2Value = max(case when RN=2 then Value else null end)
, Type3Value = max(case when RN=3 then Value else null end)
from (
select *
, rn = Row_Number() over (Partition By TypeId Order by AddedTime)
from Values_M
) a
where rn <= 3
group by BookingId