sqlpivot

Fetch data to single row from multiple rows


I have a table with these columns and data:

cid step cr_time
120 S02 08-JUL-24 08.35.19.000 AM
120 S03 08-JUL-24 01.35.19.000 PM
120 S04 09-JUL-24 02.35.19.000 PM
121 S02 09-JUL-24 09.35.19.000 AM
121 S03 09-JUL-24 02.35.19.000 PM
122 S02 10-JUL-24 10.35.19.000 AM
122 S03 10-JUL-24 03.35.19.000 PM

How can I fetch data such a way that only row exists for one cid and shows cr_time for step ('S02', 'S03') - like this:

cid S02_cr_time S03_cr_time
120 08-JUL-24 08.35.19.000 AM 08-JUL-24 01.35.19.000 PM
121 09-JUL-24 09.35.19.000 AM 09-JUL-24 02.35.19.000 PM
122 10-JUL-24 10.35.19.000 AM 10-JUL-24 03.35.19.000 PM

Solution

  • You can use PIVOT technique here. The pivot can be done using GROUP BY and some aggregation function (MIN in next example) with condition within:

    select 
        cid,
        min(case when step = 'S02' then cr_time end) S02_time,
        min(case when step = 'S03' then cr_time end) S03_time
    from t
    group by cid;
    

    Try SQL online