这是我的起始数据表的示例
我想将数据翻转为如下所示 - 对于状态 fips、年份和 id 的每个唯一组合,其中有 status1-status?状态值的数量未知,并且可能根据数据而变化。
我一直在研究pivot,但似乎无法获得正确的语法。该文档使用聚合,但我只需要转置信息。
这是一些代码和我的一些尝试。
create or replace temporary table try1
(fips integer, yr integer, id varchar(5), status varchar(10));
insert into try1
values
(20,2022,47250,'03 ACTIVE'),
(20,2022,47250,'79 TERM'),
(20,2023,47250,'79 TERM'),
(20,2022,56957,'83 TERM'),
(20,2023,56957,'03 ACTIVE'),
(20,2023,56957,'83 TERM'),
(20,2022,57645,'79 TERM'),
(20,2023,57645,'03 ACTIVE'),
(20,2023,57645,'79 TERM'),
(20,2023,57645,'83 TERM');
select *, 1 as flag from try1
pivot(sum(flag)) for status in (any order status)
order by id;
select *, 1 as flag from try1
pivot(flag) for status in (any order status)
order by id;
select * from try1
pivot(for status in (any order status))
order by id;
正如其他人建议稍后解析它,您可以使用array_unique_agg
with try1(fips, yr, id, status ) as (
select * from values
(20,2022,47250,'03 ACTIVE'),
(20,2022,47250,'79 TERM'),
(20,2023,47250,'79 TERM'),
(20,2022,56957,'83 TERM'),
(20,2023,56957,'03 ACTIVE'),
(20,2023,56957,'83 TERM'),
(20,2022,57645,'79 TERM'),
(20,2023,57645,'03 ACTIVE'),
(20,2023,57645,'79 TERM'),
(20,2023,57645,'83 TERM')
)
select
fips,
yr,
id,
array_unique_agg(status) as status_array
from try1
group by 1,2,3
order by 1,3,2;