交叉表故障(“返回和sql元组描述不兼容”)

时间:2015-12-01 21:43:34

标签: postgresql pivot crosstab

我正在尝试计算表格上的交叉表(恰好是一个简单的物化视图,但这无关紧要):

user=# select * from data;
 region |    date    | sum
--------+------------+-----
 East   | 2010-06-30 |  22
 East   | 2010-01-31 |  32
 East   | 2010-02-25 |  12
 North  | 2010-01-31 |  34
 North  | 2010-02-25 |  88
 South  | 2010-01-31 |  52
 South  | 2010-02-25 |  54
 South  | 2010-06-30 |  11
 West   | 2010-06-30 |  15
 West   | 2010-02-25 |  37
 West   | 2010-01-31 |  11
(11 rows)

当我尝试使用以下表达式计算数据的交叉表时,出现错误:

user=# SELECT * FROM
       crosstab('select region, date, sum from x order by 1') 
       AS ct (region text, d1 date, d2 date, d3 date);
ERROR:  return and sql tuple descriptions are incompatible

我不知道为什么会发生这种情况!这是源表的模式:

user=# \d data
 Materialized view "public.data"
 Column |  Type  | Modifiers 
 --------+--------+-----------
 region | text   | 
 date   | date   | 
 sum    | bigint | 

1 个答案:

答案 0 :(得分:6)

value列的类型为bigint,而不是date

SELECT * 
FROM crosstab(
    'select region, date, sum from data order by 1'
) 
AS result (region text, d1 bigint, d2 bigint, d3 bigint);

 region | d1 | d2 | d3 
--------+----+----+----
 East   | 22 | 32 | 12
 North  | 34 | 88 |   
 South  | 52 | 54 | 11
 West   | 15 | 37 | 11
(4 rows)