加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在PostgreSQL中使用行值作为列

发布时间:2020-12-13 16:03:53 所属栏目:百科 来源:网络整理
导读:由于之前的查询,我有以下品牌表,每月总销售额: 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-
由于之前的查询,我有以下品牌表,每月总销售额:

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

如何将日期值用作列,并能够用0总计填写缺失日期?

解决方法

您的示例的 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允许,也不应该使用保留字“date”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读