[英]SQL Pivoting in Teradata
I need to convert the rows into multiple output columns. 我需要将行转换为多个输出列。
I've 2 tables that I need to combine and produce the third table which is kept here. 我有2个表,我需要合并并生成保存在此处的第三个表。
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');
That's neither Pivot nor Unpivot, you want to create all possible combinations of the different types: 既不是枢轴也不是枢轴,您要创建不同类型的所有可能组合:
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
If you need to do this for different tags you can switch to: 如果您需要对其他标签执行此操作,则可以切换到:
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
Of course this hard-codes the ids, if you want them dynamically created you need Dynamic SQL in a Stored Procedure. 当然,这会对ID进行硬编码,如果要动态创建ID,则需要在存储过程中使用动态SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.