Accomplish pivot in teradata sql

前端 未结 3 1238
滥情空心
滥情空心 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)
    

提交回复
热议问题