计算postgresql中两个对应列之和的方法

way to calculate sum of two corresponded columns in postgresql

我有两个名为 "incoming" 和 "orders" 的表,我想创建名为 "stock" 的视图,该视图是使用来自传入和订单的数据生成的。

CREATE TABLE incoming
(
  id serial NOT NULL,
  model integer,
  size integer,
  color integer,
  price real,
  quanity integer,
  CONSTRAINT pk PRIMARY KEY (id),
  CONSTRAINT "incoming_model_size_color_key" UNIQUE (model, size, color)

)

CREATE TABLE orders
(
  id serial NOT NULL,
  model integer,
  size integer,
 color integer,
  price real,
  quanity integer,
  Comenttext text,
  CONSTRAINT pk_orders PRIMARY KEY (id)
)

现在我有这个肮脏的解决方案:

CREATE OR REPLACE VIEW stock AS 
 WITH total_orders AS (
             SELECT orders.model,
            orders.size,
            orders.color,
            sum(orders.quanity) AS sum
           FROM orders
          GROUP BY orders.color, orders.size, orders.model
        )
 SELECT incoming.model,
    incoming.size,
    incoming.color,
    incoming.quanity - (( SELECT
                CASE count(*)
                    WHEN 1 THEN ( SELECT total_orders_1.sum
                       FROM total_orders total_orders_1
                      WHERE incoming.model = total_orders_1.model AND incoming.size = total_orders_1.size)
                    ELSE 0::bigint
                END AS "case"
           FROM total_orders
          WHERE incoming.model = total_orders.model AND incoming.size=total_orders.size)) AS quanity
   FROM incoming;

如何使用起来更清晰简单?

示例:

 select * from incloming

 id | model | size | color | price | quanity
----+-------+------+-------+-------+--------
  1 |     1 |    6 |     5 |   550 |      15
  2 |     1 |    5 |     5 |   800 |      20


select * from orders 

 id | model | size | color | price | quanity | 
----+-------+------+-------+-------+---------+
  1 |     1 |    6 |     5 |  1000 |       1 | 
  2 |     1 |    6 |     5 |  1000 |       2 | -- sum is 3

select * from stock

 model | size | color | quanity
-------+------+-------+----------
 1     |    6 |     5 |      12 --= 15 - 3 !! excellent
 1     |    5 |     5 |      20 -- has no oerders yet

您只需要在聚合订单上左加入:

select i.model, i.size, i.color, i.quantity, 
       o.qty as ordered, 
       i.quantity - coalesce(o.qty, 0) as quantity_on_stock
from incoming i
  left join (
     select model, size, color, sum(quantity) as qty
     from orders 
     group by model, size, color
  ) o on (o.model, o.size, o.color) = (i.model, i.size, i.color);

SQLFiddle: http://sqlfiddle.com/#!15/7fbec/2

当使用您的 CTE 作为基础时,您会得到以下结果:

WITH total_orders AS (
  SELECT orders.model,
         orders.size,
         orders.color,
         sum(orders.quantity) AS sum
  FROM orders
  GROUP BY color, size, model
)
SELECT i.model,
       i.size,
       i.color,
       i.quantity - coalesce(tot.sum, 0) AS quanity
FROM incoming i
  LEFT JOIN total_orders tot on (tot.model, tot.size, tot.color) = (i.model, i.size, i.color);

CTE 或派生的 table(第一个解决方案)是否更快,您需要测试。