簡體   English   中英

如何使用 SQL 計算運行余額

[英]How To Calculate Running balance using SQL

如果我的總數量 = 100。並且它已分 4 個階段發貨,第 40、10、25、25 行等於 100。當我運行此查詢時:

有人幫我解決了這個問題。 我想要 DB2 的相同 runnable。

SET totalQty = -1;
SELECT 
  IF(@totalQty<0, pl.quantity, @totalQty) AS totalQty, 
  pr.invoiceqty, 
  @totalQty:=(@totalQty - pr.invoiceqty) AS balance 
FROM 
  purchaseorderline pl, replenishmentrequisition pr

我得到這樣的結果:

--total qty--   --invoice qty-- --balance qty--
100 40  60
100 10  90
100 25  75
100 25  70

我想要的結果:

--total qty--   --invoice qty-- --balance qty--
100 40  60
60  10  50
50  25  25
25  25  00

如果您以表格形式提供一些示例數據,而不僅僅是您從中獲得的內容,那就足夠了。

WITH MYTAB (PHASE_ID, QTY) AS
(
-- Your initial data as the result of
-- your base SELECT statement
VALUES
  (1, 40)
, (2, 10)
, (3, 25)
, (4, 25)
)
SELECT 
  QTY + QTY_TOT - QTY_RTOT  AS "total qty"
, QTY                       AS "invoice qty"
, QTY_TOT - QTY_RTOT        AS "balance qty"
FROM 
(
  SELECT 
    PHASE_ID
  , QTY
  -- Running total sum
  , SUM (QTY) OVER (ORDER BY PHASE_ID)  AS QTY_RTOT
  -- Total sum
  , SUM (QTY) OVER ()                   AS QTY_TOT
  FROM MYTAB
)
ORDER BY PHASE_ID
總數量 發票數量 余額
100 40 60
60 10 50
50 25 25
25 25 0

Marks 答案的一個變體是:

WITH MYTAB (PHASE_ID, QTY) AS
(
    -- Your initial data as the result of
    -- your base SELECT statement
    VALUES (1, 40)
         , (2, 10)
         , (3, 25)
         , (4, 25)
)
SELECT QTY_TOT  AS "total qty"
     , QTY      AS "invoice qty"
     , coalesce(lead(QTY_TOT) over (order by phase_id),0) AS "balance qty"
FROM 
( SELECT PHASE_ID
       , QTY
       -- Running total sum
       , SUM (QTY) OVER (ORDER BY PHASE_ID desc)  AS qty_tot
  FROM MYTAB
)
ORDER BY PHASE_ID

它在外層使用 lead 而不是在內層對整個 window 求和

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM