1、问题来源在使用postgresql 函数 crosstab 进行行转列时遇到的这个问题,在元数据中使用了sum函数,crosstab 无法确定返回的数据类型
出现错误写法如下:
select * from crosstab('select t1.createtime::date ,t1.property ,sum(t1.propertyvalue)
from property_value t1
where 1=1
group by t1.createtime,t1.property
order by t1.createtime desc ,t1.property')
as ct (createTime date,"chinese" int4,"english" int4,"math" int4,"music" int4,"sports" int4)
执行sql出现如下错误:SQL 错误 [42601]: 错误: return and sql tuple descriptions are incompatible
2、解决方法,正确写法如下,将sum 结果 通过 cast 函数转换一下数据类型
select * from crosstab('select t1.createtime::date ,t1.property ,cast(sum(t1.propertyvalue) as int4)
from property_value t1
where 1=1
group by t1.createtime,t1.property
order by t1.createtime desc ,t1.property')
as ct (createTime date,"chinese" int4,"english" int4,"math" int4,"music" int4,"sports" int4)
3、总结,cast的用法
3.1、字符串(varchar)转换数值(int4)
select cast('1' as int4)
3.2、时间转换(timestamp)转换日期(date)
select cast('2020-10-10 10:43:54' as date)
3.3、数值(int4)转换字符串( varchar)
select cast(1 as varchar)
最后修改于 2020-10-10 10:36:13
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

