gpt4 book ai didi

sql - 在 PostgreSQL 中使用行值作为列

转载 作者:行者123 更新时间:2023-11-29 11:27:04 25 4
gpt4 key购买 nike

我有以下 brands 表,其中包含每个 monthtotal 销售额作为先前查询的结果:

 id  |   date   | total
-----+----------+------
123 | Apr-2012 | 100
123 | Mar-2012 | 150
123 | Jan-2012 | 500
987 | Apr-2012 | 5
987 | Mar-2012 | 0.10
987 | Feb-2012 | 8

我希望实现以下目标:

 id  | Apr-2012 | Mar-2012 | Feb-2012 | Jan-2012
123 | 100 | 150 | 0 | 500
987 | 5 | 0.10 | 8 | 0

如何使用 date 值作为列并能够用总计为 0 来填充缺失的日期?

最佳答案

A crosstab()查询您的示例将如下所示:

要为生成的 NULL 值填写 0(在评论中请求),请使用 COALESCE() :

SELECT brand_id
, COALESCE(jan, 0) AS "Jan-2012"
, COALESCE(feb, 0) AS "Feb-2012"
, COALESCE(mar, 0) AS "Mar-2012"
, COALESCE(apr, 0) AS "Apr-2012"
FROM crosstab(
'SELECT brand_id, month, total
FROM brands
ORDER BY 1'

,$$VALUES ('Jan-2012'::text), ('Feb-2012'), ('Mar-2012'), ('Apr-2012')$$
) AS ct (
brand_id int
, jan numeric -- use actual data type!
, feb numeric
, mar numeric
, apr numeric);

此相关答案中的详细解释和链接:
PostgreSQL Crosstab Query

旁白:不使用保留字“date”作为列名,你也不应该,即使 Postgres 允许。

关于sql - 在 PostgreSQL 中使用行值作为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com