sql - 在 Redshift 中将多行旋转到列
问题描述
我正在寻找一种将大量行转换为列的平滑方法,而不必在临时CASE WHEN
语句中提及每一行的不同值,因为我想要转换为列的不同值的数量肯定不小。
总而言之,我有一张如下表所示的表格:
seller product
a 1
b 1
b 2
a 6
c 4
d 7
a 4
b 7
d 1
我的目标是获得一个代表每个卖家的列,该列将存储每个卖家可用的产品列表。因此,在示例中,我试图实现的输出如下所示:
a b c d
1 1 4 7
6 2 1
4 7
解决方案
您可以使用row_number()
添加序列号,然后按此聚合:
select max(case when seller = 'a' then product end) as a,
max(case when seller = 'b' then product end) as b,
max(case when seller = 'c' then product end) as c,
max(case when seller = 'd' then product end) as d
from (select t.*,
row_number() over (partition by seller order by product) as seqnum
from t
) t
group by seqnum;
注意:这是按产品排序的,因此结果与您查询中指定的顺序不完全一致。表中没有“原始”排序,因为 SQL 表表示无序(多)集。order by
如果您有首选顺序,您可以使用其他列或表达式。