【问题标题】:CrossTab function posgresql交叉表函数 postgresql
【发布时间】:2021-07-23 17:01:29
【问题描述】:

我是 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 会出错

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

任何帮助表示赞赏

【问题讨论】:

  • 使用条件聚合几乎总是比使用crosstab()更容易
  • 谢谢。你能举个例子或给我指点任何教程吗?
  • herehereherehere
  • 与您的问题无关,但是:您应该真正避免使用那些可怕的带引号的标识符。他们的麻烦比他们值得的要多得多。 wiki.postgresql.org/wiki/…
  • 感谢您的帮助。非常感谢

标签: sql postgresql pivot crosstab postgres-crosstab


【解决方案1】:

错误在最后一行。在此行中选择了 ct 中表示的列。而不是

)as ct("AccountNumber" text , "ProductCategory" text , sm numeric)

应该是

as ct(
    AccountNumber text, 
    ProductCategory1 numeric, 
    ProductCategory2 numeric, 
    ProductCategory3 numeric, 
    ..., 
    ProductCategoryN numeric)

您的GROUP BY 子句也应该只包含稍后排序的第一列和第二列。

这是一个dbfiddle 示例用于说明。或者,如果您更喜欢代码,这里有一个示例代码。

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

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2016-09-29
    • 2011-03-01
    • 2022-01-21
    相关资源
    最近更新 更多