我有以下数据:
ID CLASS VALUE
1 NHB 700905.7243
1 HBW 164216.1311
1 HBO 700905.7243
2 NHB 146023.3792
2 HBW 89543.2972
2 HBO 82152.072
3 NHB 1409818.328
3 HBW 220430.7922
3 HBO 323512.9391
4 NHB 48711.3814
4 HBW 163385.1575
4 HBO 363352.3441
我想重组为:
ID HBO HBW NHB
1 700905.7243 164216.1311 700905.7243
2 82152.072 89543.2972 146023.3792
3 323512.9391 220430.7922 1409818.328
4 363352.3441 163385.1575 48711.3814
请注意,HBW,HBO和NHB列中的值是总计(总和)。
这是我用来创建输出的脚本:
-- CREATE EXTENSION tablefunc;
SELECT *
FROM CROSSTAB
(
'SELECT _tlfd.id,
_tlfd."class",
_tlfd."value"
FROM public._tlfd
WHERE _tlfd."class" = ''HBW'' or _tlfd."class" = ''HBO'' or _tlfd."class" = ''NHB''
ORDER BY 1,2'
)
AS
(
"class" int,
"HBW" text,
"HBO" text,
"NHB" text,
--"Purpose" varchar,
"value" double precision
);
当我运行脚本时,我收到此错误:
ERROR: return and sql tuple descriptions are incompatible.
我不确定这意味着什么以及如何纠正错误。有人可以让我知道:
答案 0 :(得分:9)
这对我在Postgres 9.3上有用:
SELECT *
FROM crosstab (
$$SELECT id, class, "value"
FROM _tlfd
WHERE class = ANY ('{HBW, HBO, NHB}')
ORDER BY 1,2$$
)
AS
t ( class int, -- needs a table alias!
"HBW" float8, -- resulting columns are double precision!
"HBO" float8,
"NHB" float8
-- "value" double precision -- column does not exist in result!
);
生成所需的输出。我无法提供SQLfiddle,因为无法在那里安装其他模块。
t
)"value"
double precision
a.k.a。float8
)其余的是品味和风格。我不会使用value
作为列名,因为它是reserved word in SQL。
此相关答案的详情:
PostgreSQL Crosstab Query