Skip to content
Advertisement

Merging Rows and put values in different columns

I have the following table:

 ID   Booked         Date
100        0   2021-01-18
100        0   2020-10-05 
162        0   2021-01-14 
162        0   2021-01-01 
162        1   2020-12-30 
162        1   2020-10-01 
266        0   2021-01-14 
266        0   2020-10-05 
266        1   2020-11-06 

and want to get to this result:

 ID  BookedYMIN   BookedYMAX   BookedNMIN   BookedNMAX
100        NULL         NULL   2020-10-05   2021-01-18
162  2020-10-01   2021-12-30   2020-01-01   2021-01-14
266  2020-11-06   2020-11-06   2020-10-05   2021-01-18

An ID value in the first table occurs max 4 times:

Booked + 1 = was either marked booked the first time in database OR was either marked booked the last time in database

Booked + 0 = was either marked not-booked the first time in database OR was either marked not-booked the last time in database

In python I am able to manage this problem, but I face performance issues. Maybe someone knows how I can handle this in SQL Server Management Studio to achieve a speedup.

Advertisement

Answer

You can use conditional aggregation:

select id,
       min(case when booked = 1 then date end) as bookedymin,
       max(case when booked = 1 then date end) as bookedymax,
       min(case when booked = 0 then date end) as bookednmin,
       max(case when booked = 0 then date end) as bookednmax
from t
group by id
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement