PostgreSQL交叉表将行转置为列

时间:2019-03-27 13:30:34

标签: sql postgresql pivot

大家好,我试图将行查询结果转换为每列1行

第一个查询是从sku选择*; 结果是:

id sku  sku_code travel_code     
1   sku1    1   1
2   sku1    2   2
3   sku1    3   3
4   sku1    4   4
5   sku1    5   5
6   sku1    6   6
7   sku1    7   7
8   sku2    8   8
9   sku2    9   9
10  sku2    10  10
11  sku2    11  11
12  sku2    12  12
13  sku2    13  13
14  sku2    14  14
15  sku3    15  15
16  sku3    16  16
17  sku3    17  17
18  sku3    18  18
19  sku3    19  19
20  sku3    20  21
21  sku3    21  21

预期输出是

SKU   SKU_CODE           TRAVEL_CODE  
sku1  1  2  3   4  5  6  7  1  2  3  4  5  6  7 
sku2  8  9  10 11 12 13  14  8  9 10 11 12 13 14
sku3  15 16 17 18 19 20  21 15 16 17 18 19 20 21 

没有标题可以

2 个答案:

答案 0 :(得分:0)

您可以将groupingminmax聚合函数一起使用

with tab(sku, sku_cod, travel_code) as
(
 select 'sku1',109,'01' union all 
 select 'sku2',209,'02' union all
 select 'sku2',309,'03' union all
 select 'sku1',409,'04'   
)
select sku, min(sku_cod) as sku_cod1, max(sku_cod) as sku_cod2, 
            min(travel_code) as travel_code1, max(travel_code) as travel_code2
  from tab
 group by sku
 order by sku;

sku     sku_cod1    sku_cod2    travel_code1    travel_code2
sku1    109         409         01              04
sku2    209         309         02              03

答案 1 :(得分:0)

您正在使用Postgres,所以我建议将值存储为数组:

select sku, array_agg(sku_cod) as sku_cods
       array_agg(travel_code) as travel_codes
from t
group by sku
order by sku;

这将允许您处理两个以上的值。