postgresql - 使用 PostgreSQL 的 PIVOT

标签 postgresql

我在 PostgreSQL 12 中进行透视时遇到问题。
我必须使用一张构造笨拙的 table 。
这是一个类似于我创建的表(仅用于简单表示)-

CREATE TABLE test(Product_num INT, SN INT, Attribute VARCHAR(100), Value DECIMAL, Note VARCHAR(50) );
下一步是使用 COPY 功能导入 CSV 文件 -
COPY public.test from 'C:\File Location\test.csv' DELIMITER ',' csv HEADER;
我得到一个超过 30k 行的表,看起来像 -
Product_num |    SN    |   Attribute   |   Value   |  Note  |
    100         9225       Unit sold       50          USA
    100         9225       Unit price      4.99
    100         9225       Num_boxes       2.5
    101         9226       Unit sold       1           GER
    101         9226       Unit price      920
    101         9226       Num_boxes       2
我想要一张 table ,就像下一张 table -
Product_num |    SN    |   Unit Sold   |   Unit price   |  Num_boxes |   Note
    100     |    9225  |        50     |       4.99     |    2.5     |   USA           
    101     |    9226  |        1      |       920      |     2      |   GER  
我尝试了多种方法,包括 crosstab() 并尝试聚合一些列,但遇到了一些问题。
该表有一些需要考虑的问题——
  • 每个 SN 的属性列都不相同——这意味着每个 SN 都有不同的属性,有些相同,有些不相同。
  • 有很多空值。
  • 有很多 0 值。

  • 我希望我能尽可能好地解释自己
    谢谢

    最佳答案

    我会将所有属性聚合到一个 JSON 结构中,然后在最终查询中提取它们:

    select product_num, sn, 
           (attributes ->> 'Num_boxes')::decimal as num_boxes,
           (attributes ->> 'Unit sold')::decimal as unit_sold,
           (attributes ->> 'Unit price')::decimal as unit_price,
           note
    from  (
      select product_num, sn, max(note) as note,
             jsonb_object_agg(attribute, value) as attributes
      from test
      group by product_num, sn
    ) t
    order by product_num, sn;   
    
    如果添加了新属性,您将需要扩展外部 SELECT 列表以反射(reflect)这一点。您无法在不更改查询的情况下获得动态的列列表。在 SQL 中,在运行语句之前必须知道查询的列数和类型。

    关于postgresql - 使用 PostgreSQL 的 PIVOT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63466824/

    相关文章:

    sql - postgresql 函数 : Final statement returns bigint instead of integer

    postgresql - 如何从 plpgsql 函数返回一个整数并回滚每个修改?

    postgresql - Postgres - 临时文件大小超过 temp_file_limit

    hibernate - 如何在 JPA 2 实体中映射 postgresql "timestamp with time zone"

    ruby-on-rails - PostgreSQL、Rails 和 :order => problem

    ruby-on-rails - 我如何将 searchkick 与 pgSQL 模式/单元一起使用并循环模式?

    Java DBUnit AmbigouslyTableNameException 错误抛出

    postgresql - postgres中大型数据库的索引

    database - 将列添加到表和 View 时锁定

    python - select 语句获取所有相同的记录,但只有一个字段不同