如何在不聚合的情况下将 Teradata table 从长格式重塑为宽格式?
How to reshape a Teradata table from long to wide format without aggregation?
虽然在回答有关将长格式 table 转换为宽格式的各种问题时提供了 Teradata 的 PIVOT 函数的使用,但这些建议涉及聚合函数的使用,这是 PIVOT 的一个参数。
有没有办法 reshape/rotate 数据 而无需 聚合?
可以table这样的...
Initial
Name
A
Abel
A
Adriana
A
Alberto
B
Billy
B
Bob
C
Carla
C
Carlos
C
Cesar
C
Cristina
...变成下面的样子?
Initial
Name1
Name2
Name3
Name4
A
Abel
Adriana
Alberto
B
Billy
Bob
C
Carla
Carlos
Cesar
Cristina
这是我用来在 Teradata 16.20 中创建第一个 table 的代码:
CREATE VOLATILE TABLE MyTab (Initial varchar(1), "Name" varchar(10))
UNIQUE PRIMARY INDEX(Initial, "Name") ON COMMIT PRESERVE ROWS;
INSERT INTO MyTab values ('A','Abel');
INSERT INTO MyTab values ('A','Adriana');
INSERT INTO MyTab values ('A','Alberto');
INSERT INTO MyTab values ('B','Billy');
INSERT INTO MyTab values ('B','Bob');
INSERT INTO MyTab values ('C','Carla');
INSERT INTO MyTab values ('C','Carlos');
INSERT INTO MyTab values ('C','Cesar');
INSERT INTO MyTab values ('C','Cristina');
SELECT * FROM MyTab ORDER BY Initial, "Name";
如果知道列数,可以使用条件聚合:
select initial,
max(case when seqnum = 1 then name end) as name1,
max(case when seqnum = 2 then name end) as name2,
max(case when seqnum = 3 then name end) as name3,
max(case when seqnum = 4 then name end) as name4
from (select t.*,
row_number() over (partition by initial order by name) as seqnum
from mytab t
) t
group by initial;
虽然在回答有关将长格式 table 转换为宽格式的各种问题时提供了 Teradata 的 PIVOT 函数的使用,但这些建议涉及聚合函数的使用,这是 PIVOT 的一个参数。
有没有办法 reshape/rotate 数据 而无需 聚合?
可以table这样的...
Initial | Name |
---|---|
A | Abel |
A | Adriana |
A | Alberto |
B | Billy |
B | Bob |
C | Carla |
C | Carlos |
C | Cesar |
C | Cristina |
...变成下面的样子?
Initial | Name1 | Name2 | Name3 | Name4 |
---|---|---|---|---|
A | Abel | Adriana | Alberto | |
B | Billy | Bob | ||
C | Carla | Carlos | Cesar | Cristina |
这是我用来在 Teradata 16.20 中创建第一个 table 的代码:
CREATE VOLATILE TABLE MyTab (Initial varchar(1), "Name" varchar(10))
UNIQUE PRIMARY INDEX(Initial, "Name") ON COMMIT PRESERVE ROWS;
INSERT INTO MyTab values ('A','Abel');
INSERT INTO MyTab values ('A','Adriana');
INSERT INTO MyTab values ('A','Alberto');
INSERT INTO MyTab values ('B','Billy');
INSERT INTO MyTab values ('B','Bob');
INSERT INTO MyTab values ('C','Carla');
INSERT INTO MyTab values ('C','Carlos');
INSERT INTO MyTab values ('C','Cesar');
INSERT INTO MyTab values ('C','Cristina');
SELECT * FROM MyTab ORDER BY Initial, "Name";
如果知道列数,可以使用条件聚合:
select initial,
max(case when seqnum = 1 then name end) as name1,
max(case when seqnum = 2 then name end) as name2,
max(case when seqnum = 3 then name end) as name3,
max(case when seqnum = 4 then name end) as name4
from (select t.*,
row_number() over (partition by initial order by name) as seqnum
from mytab t
) t
group by initial;