Accomplish pivot in teradata sql

前端 未结 3 1219
滥情空心
滥情空心 2021-01-03 11:20

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            


        
相关标签:
3条回答
  • 2021-01-03 11:49

    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)
    
    0 讨论(0)
  • 2021-01-03 11:51

    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.

    0 讨论(0)
  • 2021-01-03 12:11

    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

    0 讨论(0)
提交回复
热议问题