簡體   English   中英

在 SQL 中透視數據並返回多個關聯列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM