我有一个产生以下结果集的视图:
CREATE TABLE foo
AS
SELECT client_id, asset_type, current_value, future_value
FROM ( VALUES
( 1, 0, 10 , 20 ),
( 1, 1, 5 , 10 ),
( 1, 2, 7 , 15 ),
( 2, 1, 0 , 2 ),
( 2, 2, 150, 300 )
) AS t(client_id, asset_type, current_value, future_value);
我需要将其转换为:
client_id a0_cur_val a0_fut_val a1_cur_val a1_fut_val ...
1 10 20 5 10
2 NULL NULL 0 2
我只current_value
使用交叉表使用列,就知道该怎么做。如何在目标结果集中使用current_value
并future_value
产生新列?如果我只是future_value
在crosstab(text)
查询中添加列,它会抱怨“无效的源数据SQL语句”。
我正在使用PostgreSQL 9.3.6。
一种方法是使用复合类型:
CREATE TYPE i2 AS (a int, b int);
或者,为临时使用(在会话期间注册类型):
CREATE TEMP TABLE i2 (a int, b int);
然后,根据需要运行交叉表并分解复合类型:
SELECT client_id
, (a0).a AS a0_cur_val, (a0).b AS a0_fut_val
, (a1).a AS a1_cur_val, (a1).b AS a1_fut_val
, (a2).a AS a2_cur_val, (a2).b AS a2_fut_val
FROM crosstab(
'SELECT client_id, asset_type, (current_value, future_value)::i2
FROM foo
ORDER BY 1,2'
,'SELECT * FROM generate_series(0,2)'
) AS ct (client_id int, a0 i2, a1 i2, a2 i2);
所有括号都是必需的!
基础知识crosstab()
:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句