透视数据并将单列放入具有关联行的多列中
Posted
技术标签:
【中文标题】透视数据并将单列放入具有关联行的多列中【英文标题】:Pivoting Data and putting single column into multiple columns with associated rows 【发布时间】:2020-03-17 17:32:35 【问题描述】:我在 Amazon Redshift (PostgreSQL) 中有如下所示的数据:
acct | id_cd | username
acc1 |123 | kchalm
acc1 |123 | rsmith
acc1 |123 | ehamon
acc1 |123 | ljenin
acc2 |234 | kchalm
acc2 |234 | rtheis
acc3 |345 | jbalvi
acc3 |345 | twoods
acc3 |345 | jli
acc4 |345 | rshant
我需要它看起来像这样。
acct | id_cd |username1|username2|username3
acc1 |123 | kchalm | rsmith | ehamon
acc1 |123 | ljenin | |
acc2 |234 | kchalm | rtheis |
acc3 |345 | jbalvi | twoods | jli
acc4 |345 | rshant | |
我已尝试执行以下操作并取得了一些成功。为了创建我的 3 个用户名列,我使用带有 WHERE 条件的连接将数据从视图中提取出来,次数不限。但是,我不禁觉得有一种比我现在这样做的方式更好的方法来自动化这个过程。有什么建议吗?
SELECT
ut.acct,
ut.id_code,
ut.username,
ROW_NUMBER() OVER(PARTITION BY ut.account_code
ORDER BY
ut.username DESC) AS row_num
FROM
orig_user_table ut ;
select
a.acct
,a.id_cd
,a.username1
,b.username2
FROM
(
SELECT
acct,
id_cd,
username AS username1
FROM
vw_user_table_nums
WHERE
row_num = 1) a
LEFT JOIN (
SELECT
acct,
username AS username2
FROM
vw_user_table_nums
WHERE
row_num = 2) b ON
a.acct = b.acct
...
【问题讨论】:
【参考方案1】:从您现有的子查询开始,一种方法使用条件聚合而不是连接:
select
acct,
id_code,
max(case when rn = 1 then username end) username1,
max(case when rn = 2 then username end) username2,
max(case when rn = 3 then username end) username3
from (
select
ut.*,
row_number() over(partition by ut.account_code order by ut.username desc) as rn
from orig_user_table ut
) t
group by acct, id_code
order by acct, id_code;
【讨论】:
以上是关于透视数据并将单列放入具有关联行的多列中的主要内容,如果未能解决你的问题,请参考以下文章