我是postgresql的新手,交叉表更新,但是从我所读到的情况来看,下面的查询应该可以工作:
select * from crosstab(
$$select distinct "AccountNumber" , "ProductCategory", sum("ProductQuantity") sm
from "MsfDataRecords" mdr
group by "ProductCategory", "AccountNumber", "ProductQuantity"$$
)as ct("AccountNumber" text , "ProductCategory" text , sm numeric)但是这与SQL Error [42601]: ERROR: return and sql tuple descriptions are incompatible有关的错误
我检查了所有的数据类型,它们是正确的。不过,我不确定这是否与和函数有关。
感谢你的任何帮助
发布于 2021-04-30 11:47:13
错误在最后一行。ct中表示的列在这一行中被选中。而不是
)as ct("AccountNumber" text , "ProductCategory" text , sm numeric)它应该是
as ct(
AccountNumber text,
ProductCategory1 numeric,
ProductCategory2 numeric,
ProductCategory3 numeric,
...,
ProductCategoryN numeric)您的GROUP BY子句还应该只包括后面排序的第一列和第二列。
下面是一个[医]小提琴示例以进行说明。或者,如果您喜欢代码,这里有一个示例代码。
CREATE TABLE MsfDataRecords(
AccountNumber text,
ProductCategory text,
ProductQuantity numeric
)
;
INSERT INTO MsfDataRecords(AccountNumber, ProductCategory, ProductQuantity) VALUES
('A1', 'Food', 3),
('A1', 'Food', 1),
('A2', 'Food', 3),
('A2', 'Electronics', 2),
('A2', 'Fashion', 10)
;
SELECT * FROM CROSSTAB(
$$
SELECT AccountNumber , ProductCategory, SUM(ProductQuantity) AS sm
FROM MsfDataRecords AS mdr
GROUP BY 1,2
ORDER BY 1,2
$$
)AS ct(
AccountNumber text,
Food numeric,
Electronics numeric,
Fashion numeric
)
;注意,这样的旋转只在PostgreSQL中起作用。
https://stackoverflow.com/questions/67332408
复制相似问题