Terdata:将多个字段组合成具有多个Colums的Single Row

时间:2015-06-17 00:54:10

标签: sql pivot teradata transpose

我希望在teradata中实现以下转换:将多行合并为一行,并将第三列中的值转换为单独的列。请参阅链接中给出的图像。我有以下约束,seq_id列是可伸缩的。

数据:

ticket_num     seq_id    err_cde    
---------------------------------
AKOZ01         a         23     
AKOZ02         a         51     
AKOZ03         a         48     
AKOZ04         a         7      
AKOZ05         a         10     
AKOZ06         a         20     
AKOZ07         b         51     
AKOZ08         b         51     
AKOZ10         b         48     
AKOZ11         b         20     
AKOZ12         b         5      
AKOZ13         c         48     
AKOZ14         c         23     
AKOZ15         c         7      
AKOZ16         c         10     
AKOZ17         c         10     
AKOZ18         c         7      
AKOZ19         d         20     
AKOZ20         d         10     
AKOZ21         d         7      
AKOZ22         d         7      
AKOZ23         d         48     
AKOZ24         d         10     
AKOZ25         d         51     

结果:

seq_id    err_cde1    err_cde2    err_cde3    err_cde4    err_cde5    err_cde6    err_cde7      
-------------------------------------------------------------------------------------------
a     23          51          48           7            10           20           0     
b     51          51          48           20           5            0            0     
c     48          23          7            10           10           7            0     
d     20          10          7            7            48           10           51        

Sample Data

1 个答案:

答案 0 :(得分:1)

这是标准SQL方法,根据ticket_num分配行号,然后执行MAX(CASE):

SELECT
   seq_id,
   MAX(CASE WHEN rn = 1 THEN err_cde ELSE 0 end) AS err_cde1,
   MAX(CASE WHEN rn = 2 THEN err_cde else 0 end) AS err_cde2,
   MAX(CASE WHEN rn = 3 THEN err_cde else 0 end) AS err_cde3,
   MAX(CASE WHEN rn = 4 THEN err_cde else 0 end) AS err_cde4,
   MAX(CASE WHEN rn = 5 THEN err_cde else 0 end) AS err_cde5,
   MAX(CASE WHEN rn = 6 THEN err_cde else 0 end) AS err_cde6,
   MAX(CASE WHEN rn = 7 THEN err_cde ELSE 0 end) AS err_cde7
FROM
 (
   SELECT
      seq_id,
      err_cde,
      ROW_NUMBER()
      OVER (PARTITION BY seq_id
            ORDER BY ticket_num) AS rn
   FROM tab
 ) AS dt
GROUP BY seq_id