【发布时间】:2019-05-12 20:55:40
【问题描述】:
下午好,我正在使用 POSTGRESql 9.2 版,我正在尝试使用交叉表函数来转置表上的两列,以便以后可以将其加入到不同的 SELECT 查询中。
我已经安装了 tablefunc 扩展。
但是我不断收到这个“返回和 SQL 元组描述不兼容”的错误,这似乎是因为类型转换。
我不需要它们是特定类型。
我原来的 SELECT 查询是这样的
SELECT inventoryid, ttype, tamount
FROM inventorytesting
这给了我以下结果:
inventoryid ttype tamount
2451530088940460 7 0.2
2451530088940460 2 0.5
2451530088940460 8 0.1
2451530088940460 1 15.7
8751530077940461 7 0.7
8751530077940461 2 0.2
8751530077940461 8 1.1
8751530077940461 1 19.2
我的目标是:
inventoryid 7 2 8 1
8751530077940461 0.7 0.2 1.1 19.2
2451530088940460 0.2 0.5 0.1 15.7
“ttype”字段有 49 个不同的值,例如“7”、“2”、“8”、“1”,它们是固定的。
'tamount' 字段的值会根据 'inventoryid' 字段的不同而变化,但总会有 49 个,即使它的值为零。它永远不会是“空的”。
我尝试了一些我可以在互联网上找到的变体,总结如下:
SELECT *
FROM crosstab (
$$SELECT inventoryid, ttype, tamount
FROM inventorytesting
WHERE inventoryid = '2451530088940460'
ORDER BY inventoryid, ttype$$
)
AS ct("inventoryid" text,"ttype" smallint,"tamount" numeric)
inventorytesting 表上的字段类型是
select column_name, data_type from information_schema.columns
where table_name = 'inventorytesting'
结果:
column_name data_type
id bigint
ttype smallint
tamount numeric
tunit text
tlessthan smallint
plantid text
sessiontime bigint
deleted smallint
inventoryid text
docdata text
docname text
labid bigint
任何指针都会很棒。
【问题讨论】:
标签: postgresql