如何对额外列中的两列行元素求和?

How to sum two column row elements in extra column?

我是 FULL OUTER JOIN 两个 tables Givens in db<>fiddle。第一个 table 名字是 product_purchase,第二个 table 名字是 sales_return。它们如下:

SELECT *来自 'product_purchase'

date invoice_no product_id purchase_quantity price
2021-01-01 10:00:00 p-101 A-1 100 100
2021-01-02 11:00:00 p-102 A-1 90 90
2021-01-03 12:00:00 p-103 A-1 200 200
2021-01-04 13:00:00 p-104 A-1 250 250

SELECT *来自 'sales_return'

date invoice_no product_id sales_return_quantity price
2021-01-01 10:00:00 r-101 A-1 10 10
2021-01-04 13:00:00 r-104 A-1 25 25

我想对额外列中的 product_purchase table 列 purchase_quantity 行元素和 sales_return table 列 sales_return_quantity 行元素求和全部的。按照代码 Givens in db<>fiddle,我写的就是这样做的。

SELECT pp.`date`, pp.`invoice_no`, pp.`product_id`, pp.`purchase_quantity`, sr.`sales_return_quantity`, sum(pp.`purchase_quantity`) OVER (ORDER BY pp.date) AS total
FROM  product_purchase pp
       LEFT JOIN sales_return sr
          ON pp.product_id = sr.product_id AND pp.product_id != sr.product_id
UNION ALL
SELECT sr.`date`, sr.`invoice_no`, sr.`product_id`, pp.`purchase_quantity`, sr.`sales_return_quantity`, sum(sr.`sales_return_quantity`) OVER (ORDER BY sr.date) AS total
FROM   sales_return sr
       LEFT JOIN product_purchase pp
         ON pp.product_id = sr.product_id AND pp.product_id != sr.product_id
WHERE  pp.product_id IS NULL
ORDER BY pp.`date`

它分别对总列 table 求和:

total
100
10
190
390
640
35

需要以下结果:

total
100
110
200
400
650
675

使用 UNION ALLSUM() window 函数代替 FULL 连接:

SELECT date, invoice_no, product_id, purchase_quantity, sales_return_quantity,
       SUM(COALESCE(purchase_quantity, 0) + COALESCE(sales_return_quantity, 0))
       OVER (ORDER BY date, sales_return_quantity IS NOT NULL) total
FROM (
  SELECT date, invoice_no, product_id, purchase_quantity, null sales_return_quantity
  FROM product_purchase
  UNION ALL
  SELECT date, invoice_no, product_id, null purchase_quantity, sales_return_quantity
  FROM sales_return
)
ORDER BY date, sales_return_quantity IS NOT NULL

参见demo