如何使用 SQL 将这四行转换为列
How can I convert these four rows into columns using SQL
我想获取步骤 table 的行作为新 table
的列
步数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
这些是 table 转换为列的步骤的行。
新建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
做一个GROUP BY
。使用case
表达式做条件聚合:
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
我想获取步骤 table 的行作为新 table
的列步数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
这些是 table 转换为列的步骤的行。
新建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
做一个GROUP BY
。使用case
表达式做条件聚合:
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