两个表的 Postgresql 交叉表

Postgresql Crosstab Over Two Tables

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

northwind database schema

我正在尝试了解如何在同时使用订单和 order_details table 的同时执行交叉表。交叉表包括来自订单 table 的 employee_id 和 ship_country 以及来自 order_details table

的 unit_price

来自订单的示例数据 table:

sample data orders table

示例数据来自 order_details table:

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 的关系。我也毫无问题地执行了 运行 'create extension tablefunc;' 命令。

Postgres 交叉表 函数 期望查询字符串作为 参数 并在 "different context" 中使用它的结果来调用该函数的查询。由于上下文的这种差异,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);

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

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

作为对 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;

针对每个国家/地区重复求和案例(从 mobile/on 移动 SO 发帖是一种糟糕的体验 - 将它们全部输入真的很辛苦,抱歉)。更改聚合函数(max、sum、avg 等)以更改网格中数据的累积方式