postgres select 查询中更简单的聚合函数

Simpler aggregate function in postgres select query

我必须 运行 在我的 select 查询中进行一些计算,以获取动态值,例如已售出库存项目收到的利润。公式为 (price minus discounts) - (total expenses) = profit

我的查询工作正常,但我有很多这样的行,所以其他人完全无法阅读。有没有办法为我的各种聚合函数或强制转换分配变量或其他东西?

这是我的查询的更简单版本:

select
    ...
    (sum(cast(ti.price as integer)) - sum(floor(cast(ti.discount as float)))) - sum(cast("exp".price as integer))) as profit,
    ...
from inventory as inv
    left join transaction_item as ti on ti.inventory_id = inv.id
    left join expense as exp on exp.inventory_id = inv.id
    ...
where
    ...
group by inv.id

对于上下文:

我想做什么而不是那个长函数链:

((price_total - total_discounts) - total_expenses) as profit

...我在某处定义了每个变量。这是可能的还是我需要接受这个查询会很混乱?

您可以使用 CTE(通用 Table 表达式)生成具有名称和类型的计算列。然后,您可以在后续的 CTE 或主查询中使用它们。

下面的示例定义了一个名为 inv_total 的 CTE,我们稍后将在主查询中使用它。此 CTE 具有三个计算列 price_totaltotal_discountstotal_expenses:

with
inv_total as ( -- first we define a CTE
  select
    ...
    sum(cast(ti.price as integer)) as price_total,
    sum(floor(cast(ti.discount as float))) as total_discount,
    sum(cast("exp".price as integer)) as total_expenses
    ...
  from inventory as inv
    left join transaction_item as ti on ti.inventory_id = inv.id
    left join expense as exp on exp.inventory_id = inv.id
    ...
  where
    ...
  group by inv.id
)
select -- now the main query uses the CTE
  price_total - total_discounts - total_expenses as profit
from inv_total;

您可以在多个步骤中链接 CTE(用逗号分隔它们)以计算临时值并继续处理。上面的例子只有一个步骤。