SQL 在 Teradata 中进行透视

SQL Pivoting in Teradata

我需要将行转换为多个输出列。

我有 2 个 table,我需要合并并生成第三个 table,保存在这里。

CREATE MULTISET TABLE TAG
( TAG VARCHAR(100), 
  ID VARCHAR(100)
) PRIMARY INDEX (TAG,ID);

INSERT INTO TAG VALUES('L2250','I14299');
INSERT INTO TAG VALUES('L2250','I14300');
INSERT INTO TAG VALUES('L2250','I14301');

CREATE MULTISET TABLE IDS
( ID VARCHAR(100),
  TYPE VARCHAR(100),
  DESCR VARCHAR(100)
) ;

INSERT INTO IDS VALUES ('I14299','Exposure','Bills');
INSERT INTO IDS VALUES ('I14299','Exposure','Certificates');
INSERT INTO IDS VALUES ('I14299','Exposure','NCDS');
INSERT INTO IDS VALUES ('I14300','Currency','GB');
INSERT INTO IDS VALUES ('I14300','Currency','AU');
INSERT INTO IDS VALUES ('I14301','Rate','NOT FIXED');
INSERT INTO IDS VALUES ('I14301','Rate','FIXED');

这既不是 Pivot 也不是 Unpivot,您想创建不同类型的所有可能组合:

SELECT *
FROM 
 ( SELECT t.tag, i.descr AS I14299
   FROM tag AS t JOIN ids AS i
     ON t.id = i.id
   WHERE i.id = 'I14299'
 ) AS e
CROSS JOIN
 ( SELECT descr AS I14300
   FROM ids
   WHERE id = 'I14300'
 ) AS c
CROSS JOIN
 ( SELECT descr AS I14301
   FROM ids
   WHERE id = 'I14301'
 ) AS r

如果您需要为不同的标签执行此操作,您可以切换到:

SELECT e.*, c.descr, r.descr
FROM 
 ( SELECT t.tag, i.descr AS I14299
   FROM tag AS t JOIN ids AS i
     ON t.id = i.id
   WHERE t.id = 'I14299'
 ) AS e
JOIN
 ( SELECT t.tag, descr AS I14300
   FROM tag AS t JOIN ids AS i
     ON t.id = i.id
   WHERE t.id = 'I14300'
 ) AS c
ON e.tag = c.tag   
JOIN
 ( SELECT t.tag, descr AS I14301
   FROM tag AS t JOIN ids AS i
     ON t.id = i.id
   WHERE t.id = 'I14301'
 ) AS r
ON e.tag = r.tag

当然,这对 ID 进行了硬编码,如果您希望动态创建它们,则需要在存储过程中动态 SQL。