PIVOT implementation in TD

2019-06-14 08:11发布

I want to pivot my data and i am aware that we have Pivot function in teradata 16. I am not sure how to use it. I am aware of other methods like max(case...) but my data set is large so i can't use that.

Can anyone tell me how to use pivot here:

SERV_PROVIDER_ID    CALL_START_DT   cnt1    
50003                  4/15/2018    25,117  
50003                  4/16/2018    65,630  
50003                  4/17/2018    63,880  
50003                  4/18/2018    40,080  

Want data like

SERV_PRIDER_ID  CALL_START_DT1 CNT1 CALL_START_DT2  CNT2 CALL_START_DT3 CNT3

I am only looking for 4 days data.

Thanks for your help.

1条回答
祖国的老花朵
2楼-- · 2019-06-14 08:19

When those four dates are known:

SELECT *
FROM mytab
PIVOT
 ( Sum(cnt1) 
   FOR CALL_START_DT
    IN (DATE'2018-04-15'
       ,DATE'2018-04-16'
       ,DATE'2018-04-17'
       ,DATE'2018-04-18'
       )
 ) AS dt;

But your expected result looks like you want those days dynamically:

WITH cte AS 
 (
   SELECT t.*,
      Row_Number()
      Over (PARTITION BY SERV_PROVIDER_ID
            ORDER BY CALL_START_DT) AS rn
   FROM mytab AS t
 )
SELECT * 
FROM cte
PIVOT
 ( Min(CALL_START_DT) AS CALL_START_DT,
   Sum(cnt1) AS Cnt
   FOR rn
    IN (1 
       ,2
       ,3
       ,4
       )
 ) AS dt;
查看更多
登录 后发表回答