Accomplish pivot in teradata sql

大憨熊 提交于 2019-11-29 23:09:05

问题


Say I have a query that returns values like this:

id    type     value
aaa   1a        10
aaa   1b        20
aaa   1c        7
bbb   2a        10
bbb   1a        5

There are > 50 million rows and 240 possible "types". I want to make a pivot where there is one row for each id and each type is it's own column:

id   1a   1b   1c   2a
aaa  10   20   7    
bbb  5              10

I can do this in SQL server but I don't know how to do it in Teradata. There are too many columns for me to make CASE statements. However, each distinct type is in a table field, if that's any help.


回答1:


There is no pivot function in Teradata SQL. A similar question was answered here - teradata sql pivot multiple occurrences into additional columns.

To best achieve what you wanted without having to write out 250 cases manually, you should use ordered analytical functions in some kind of a loop or a set. Try searching "loop" tag from Teradata Developer Exchange - http://developer.teradata.com/tag/loop

Here's how I would do it: Use another programming language (Python) to reiterate over a text/premade SQL and change it's only two variables 250 times, from 1 to 250, and generate the full long sql. Only reiterate the part between SELECT DISTINCT id and last FROM mytable row:

SELECT DISTINCT
id
-- reiteration starts here
,(SELECT SUM(value) -- assuming you have unique types for every id
  FROM (SELECT DISTINCT
    id
    ,value
    ,type
    FROM mytable
    QUALIFY (RANK() OVER(PARTITION BY type ORDER BY id ASC))=1 -- variable 1
    )
) AS type_1 -- variable 2
-- reiteration ends here
FROM mytable

You can use this python:

for i in range(1,251):
    print " \
,(SELECT SUM(value) -- assuming you have unique types for every id \
FROM (SELECT DISTINCT \
id \
,value \
,type \
FROM mytable \
QUALIFY (RANK() OVER(PARTITION BY type ORDER BY id ASC))=%d -- variable 1 \
) \
) AS type_%d -- variable 2 \
" % (i,i)



回答2:


There is a TD_UNPIVOT function which was added in TD 14.10 can be found in TD_SYSFNLIB.

TD_UNPIVOT Function

The PIVOT and UNPIVOT SQL commands were added in Teradata 16 and they can be found in the SQL Functions, Operators, Expressions, and Predicates manual. At this time, I can't find them in an online manual so you will need to download the PDF from Teradata.com.

New TD 16 Features PIVOT and UNPIVOT




回答3:


Using PIVOT function in Teradata 16 it could look like this (assuming your types are in a table called mytypetable):

SELECT 
  *
FROM 
  mytable PIVOT (SUM("value") FOR "type" IN (SELECT "Type" FROM mytypetable)) AS Temp_pivot
ORDER BY 
  id

One drawback is that you cannot decide on the order of the columns though.



来源:https://stackoverflow.com/questions/22335854/accomplish-pivot-in-teradata-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!