简体   繁体   中英

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM