首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CrossTab函数偏序

CrossTab函数偏序
EN

Stack Overflow用户
提问于 2021-04-30 10:33:23
回答 1查看 224关注 0票数 0

我是postgresql的新手,交叉表更新,但是从我所读到的情况来看,下面的查询应该可以工作:

代码语言:javascript
复制
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有关的错误

我检查了所有的数据类型,它们是正确的。不过,我不确定这是否与和函数有关。

感谢你的任何帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-30 11:47:13

错误在最后一行。ct中表示的列在这一行中被选中。而不是

代码语言:javascript
复制
)as ct("AccountNumber" text , "ProductCategory" text , sm numeric)

它应该是

代码语言:javascript
复制
as ct(
    AccountNumber text, 
    ProductCategory1 numeric, 
    ProductCategory2 numeric, 
    ProductCategory3 numeric, 
    ..., 
    ProductCategoryN numeric)

您的GROUP BY子句还应该只包括后面排序的第一列和第二列。

下面是一个[医]小提琴示例以进行说明。或者,如果您喜欢代码,这里有一个示例代码。

代码语言:javascript
复制
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中起作用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67332408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档