使用ANSI SQL的动态数据透视

时间:2017-04-08 16:00:26

标签: teradata ansi-sql dynamic-pivot

我有一个表test123,其中的数据如下

create table test123
(
id varchar(3),
typ varchar(2),
val int
);

Select * from test123 order by id,typ;

id      typ val
aaa     1a  10
aaa     1b  20
aaa     1c  7
aaa     2a  10
bbb     1a  5
bbb     1d  17

现在我想使用ANSI SQL(可以在Teradata中工作),如下所示输出

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

现在,类型的数量可以更改,因此会有更多列。

帖子Accomplish pivot in teradata sql下面的sql没有解决我的问题

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

我也尝试过链接Accomplish pivot in teradata sql中给出的python代码,但没有得到预期的结果

import pymysql

db = pymysql.connect(host="localhost", user="koushik", passwd="koushik", db="koushik")

cur = db.cursor()

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

db.close()

0 个答案:

没有答案