【问题标题】:Postgresql Crosstab Over Two Tables两个表上的 Postgresql 交叉表
【发布时间】:2018-11-17 20:33:51
【问题描述】:

使用如下所示的北风数据库进行练习:

northwind database schema

我试图了解如何在同时使用订单和 order_details 表时执行交叉表。交叉表包括订单表中的employee_id 和ship_country 以及order_details 表中的unit_price

来自订单表的示例数据:

sample data orders table

order_details 表中的示例数据:

sample data order_details table

我认为以下方法可行,但无法运行:

with my_table as (
select o.employee_id, o.ship_country, od.unit_price
    from orders o
    join order_details od on o.order_id = od.order_id)

    select *
    from crosstab('select employee_id, ship_country, unit_price from my_table')
    as final_result(EmployeeID text, Austria numeric, Finland numeric, Italy numeric, France numeric, 
                    Germany numeric, Brazil numeric, Belgium numeric, Switzerland numeric);

非常感谢您提出任何想法以及如何使其发挥作用。问题似乎是它不承认与 my_table 的关系。我确实运行了“创建扩展表函数;”命令也没有问题。

【问题讨论】:

  • Crosstab == pivot ?

标签: sql postgresql join crosstab


【解决方案1】:

Postgres 交叉表 函数 期望查询字符串作为 参数 并在调用该函数的查询的“不同上下文”中使用该结果。由于这种上下文差异,my_table cte 根本不适用于函数的内部。

select *
from crosstab('select o.employee_id, o.ship_country, od.unit_price from orders o
               join order_details od on o.order_id = od.order_id')
as final_result(EmployeeID text, Austria numeric, Finland numeric, Italy numeric, France numeric, 
                Germany numeric, Brazil numeric, Belgium numeric, Switzerland numeric);

函数参数需要一个完整的查询,在这种情况下,使用公用表表达式根本没有优势。只需将cte的sql移到函数参数中即可。

有关交叉表的更多信息,我建议this answerthis

【讨论】:

    【解决方案2】:

    作为对 UBA 答案的补充,如果您想使用 cte,请以更标准的方式/使用普通 sql 进行交叉表:

    with my_table as (
    select o.employee_id, o.ship_country, od.unit_price
    from orders o
    join order_details od on o.order_id = od.order_id)
    
    select employee_id,
      Sum(case when ship_country = 'Germany' then unit_price end) as Germany,
      Sum(case when ship_country = 'Brazil' then unit_price end) as Brazil,
      ...
      FROM my_table
      GROUP BY
        employee_id;
    

    在每个国家/地区重复总和情况(从移动/移动 SO 发布是一种糟糕的体验 - 将它们全部输入真的很难,抱歉)。更改聚合函数(max、sum、avg 等)以更改网格中数据的累积方式

    【讨论】:

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