[英]Pivoting Data and putting single column into multiple columns with associated rows
[英]Pivoting data in SQL and returning multiple associated columns
我有一个包含以下字段的表:user_id、tag、tag_certification_date、tag_review_date 和 tag_expiration_date。 每个用户编号可以有多个标签,在这种情况下,用户将在表中有多行。 每个标签一个。 有 5 个可能的标签 A、B、C、D、E。
示例数据
user_id tag tag_certification_date tag_review_date tag_expiration_date
------- ---- ----------------------- ----------------- --------------------
001 A 2020-01-01 2020-06-01 2021-01-01
001 B 2020-02-01 2020-07-01 2021-08-01
001 C 2020-03-01 2020-08-01 2021-03-01
我已经能够使用 PIVOT 来创建一个查询,该查询可以部分完成,但是我在包含所有日期字段时遇到了问题。 我希望查询将用户的所有数据作为一行返回。 所以每个标签和每个标签对应的 tag_certification_date、tag_review_date 和 tag_expiration_date。
你似乎想要:
select user_id,
max(case when tag = 'A' then tag_certification_date end) as tag_certification_date_a,
max(case when tag = 'A' then tag_review_date end) as tag_review_date_a,
max(case when tag = 'A' then tag_expiration_date end) as tag_expiration_date_a,
max(case when tag = 'B' then tag_certification_date end) as tag_certification_date_b,
max(case when tag = 'B' then tag_review_date end) as tag_review_date_b,
max(case when tag = 'B' then tag_expiration_date end) as tag_expiration_date_b,
. . .
from t
group by user_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.