Home > Blockchain >  How can I convert these four rows into columns using SQL
How can I convert these four rows into columns using SQL

Time:10-20

I would like to get the rows for steps table as columns for the new table

Steps table

ID |Steps | Steps_Date
1 | Create | 5/9/2020
1 |Schedule | 5/11/2020
1| Complete | 5/12/2020
1| Request | 5/10/2020
2| Request | 5/12/2021

These are the rows for the steps table converted to columns.

New table

ID | Create | Request | Schedule | Complete
1 | 5/9/2020|5/10/2020|5/11/2020|5/12/2020
2 | Null | 5/12/2021 | Null | Null 

CodePudding user response:

Do a GROUP BY. Use case expressions to do conditional aggregation:

select id,
       max(case when Steps = 'Create'   then Steps_Date end) as create_date,
       max(case when Steps = 'Request'  then Steps_Date end) as Request_date,
       max(case when Steps = 'Schedule' then Steps_Date end) as Schedule_date,
       max(case when Steps = 'Complete' then Steps_Date end) as Complete_date
from Steps_table
group by id
  • Related