【问题标题】:PostgreSQL subquery calculations from unrelated models来自不相关模型的 PostgreSQL 子查询计算
【发布时间】:2016-12-05 17:28:13
【问题描述】:

我一直在尝试不同的方法来做到这一点,但不确定如何以最好的方式进行。

我有几个模型都与父“客户端”模型相关。对于这个例子(这与我的实际问题无关)让我们假设客户有电子邮件订单和电话订单。因此,每个电子邮件订单或电话订单都与一个客户相关,但彼此之间没有任何关系。

我想对客户运行查询并返回所有客户,以及每个客户订单中的一个字段的总和(例如:美元金额 - 两个子模型中都存在的一个字段)以及总 TAX对于两个订单(因此要返回两个聚合列)。

一种方法是在每种情况下运行一个子查询和另一个子查询 - 外部子查询将两个内部子查询的总数相加。但是在这种情况下,当我尝试捕获两个字段时,我收到一条错误消息,说子查询只能返回一列。

构建这个的最佳方式是什么?

编辑:

表结构(为了示例的目的,使用具有相同结构的电子邮件/电话订单进行了大量简化)如下:

客户表 -

CREATE TABLE clients_client
(
  id integer NOT NULL,
  deleted boolean NOT NULL,
  company_name character varying(100)
)

电子邮件订单 -

CREATE TABLE clients_emailorders
(
  id serial NOT NULL,
  added_at timestamp with time zone NOT NULL,
  deleted boolean NOT NULL,
  tx_category integer NOT NULL,
  status integer NOT NULL,
  amount numeric(18,8) NOT NULL,
  tax numeric(18,8) NOT NULL,
  tx_id character varying(200) NOT NULL,
  completed_at timestamp with time zone,
  notes text,
  client_id integer NOT NULL
)

电话订购 -

CREATE TABLE clients_phoneorders
(
  id serial NOT NULL,
  added_at timestamp with time zone NOT NULL,
  deleted boolean NOT NULL,
  tx_category integer NOT NULL,
  status integer NOT NULL,
  amount numeric(18,8) NOT NULL,
  tax numeric(18,8) NOT NULL,
  tx_id character varying(200) NOT NULL,
  completed_at timestamp with time zone,
  notes text,
  client_id integer NOT NULL
)

我想运行的查询(我目前没有任何工作,所以这是说明性的)大致如下:

SELECT "clients_client"."id", "clients_client"."company_name", total_order_amount, total_order_tax
FROM "clients_client"
WHERE "clients_client"."deleted" = False

其中“total_order_amount”是两个子模型的所有订单金额的总和,“total_order_tax”是两个子模型的税额总和。

我应该补充一点,每个客户可以有零个或多个每种订单类型。

【问题讨论】:

  • saying a Subquery can only return one column. 这是一个标量子查询。通常,子查询可以产生多于一行乘以多于一列:实际上是一个表表达式。只需给它一个别名并引用它的字段。
  • edit 您的问题为有问题的表和您正在使用的查询添加create table 语句。 Formatted 文本no screen shots
  • 我已经编辑了上面的原始问题以包含这个。

标签: sql postgresql subquery


【解决方案1】:

使用UNION ALL 运算符合并两个订单表,并将结果连接到客户表:

SELECT c.company_name,
    sum( o.amount ) as amount,
    sum( o.tax ) as tax
FROM clients_client c
JOIN (
    SELECT client_id ,  amount, tax
    FROM clients_phoneorders
    UNION ALL
    SELECT client_id ,  amount, tax
    FROM clients_emailorders
) o
ON o.client_id = c.id
GROUP BY c.company_name

【讨论】:

  • 即使两个子模型彼此完全不同,您是否会推荐这种方法,只要它们都具有我要操作的 client_id 字段和金额字段(不像上面的示例) ?
  • 是的。表的结构可以完全不同,没关系。文档中解释了唯一的限制:postgresql.org/docs/current/static/queries-union.htmlthe two queries must be "union compatible", which means that they return the same number of columns and the corresponding columns have compatible data types, as described in Section 10.5.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多