簡體   English   中英

如何將上一行的值傳遞到當前行?

[英]How to pass the value of previous row to current row?

如何將上一行的結果傳遞給當前行的計算

給定單位和成本,我需要獲取每筆交易的平均成本:

公式:

  1. 平均成本是交易成本之和
  2. 如果類型為Sub,則Trx成本等於成本
  3. 如果“類型”為紅色,則“ Trx成本”為“單位” *(先前TRX成本之和/先前單位之和)
|  Row | Type | Unit | Cost | TrxCost  | Ave_cost |
|  1   |Sub   | 0.2  | 1000 |  1000    | 1000     |
|  2   |Sub   | 0.3  | 2500 |  2500    | 3500     |
|  3   |Sub   | 0.1  | 600  |  600     | 4100     |
|  4   |Red   |- 0.2 |-1100 | -1366.67 | 2733.33  |
|  5   |Sub   | 0.3  | 1000 |  1000    | 3733.33  |
|  6   |Red   | -0.6 | -600 | -3200    | 533.33   |

更新:

訂單基於行號。

謝謝。

您可以使用遞歸CTE

WITH cte (row_num,
     type,
     unit,
     sum_of_unit,
     cost,
     trxcost,
     ave_cost
) AS (
     SELECT row_num,
            type,
            unit,
            unit AS sum_of_unit,
            cost,
            cost AS trxcost,
            cost AS ave_cost
     FROM t
     WHERE row_num IN (
          SELECT MIN(row_num)
          FROM t
     )
     UNION ALL
     SELECT t.row_num,
            t.type,
            t.unit,
            c.sum_of_unit + t.unit AS sum_of_unit,
            t.cost,
            CASE t.type
                 WHEN 'Sub'   THEN t.cost
                 WHEN 'Red'   THEN t.unit * ( c.ave_cost / c.sum_of_unit )
            END
       AS trxcost,
            c.ave_cost + CASE t.type
                 WHEN 'Sub'   THEN t.cost
                 WHEN 'Red'   THEN t.unit * ( c.ave_cost / c.sum_of_unit )
            END AS ave_cost
     FROM t
     JOIN cte c ON t.row_num = c.row_num + 1
)
SELECT * FROM cte

Dbfiddle演示

您可以theTrxCost執行此操作:一次獲取theTrxCost ,然后一次獲取Ave_cost

順便說一句,您所說的“平均”是一個總計。 您只是在增加價值。

您需要帶有ROWS BETWEEN子句的窗口函數。 (在SUM(...) OVER (ORDER BY ...)情況下,這隱含在BETWEEN UNBOUNDED PRECEDING AND CURRENT ,但是)。

select 
  id, type, unit, cost, round(trxcost, 2) as trxcost,
  round(sum(trxcost) over (order by id), 2) as ave_cost
from
(
  select 
    id, type, unit, cost,
    case 
      when type = 'Sub' then cost 
      else
        unit *
        sum(cost) over (order by id rows between unbounded preceding and 1 preceding) /
        sum(unit) over (order by id rows between unbounded preceding and 1 preceding)
    end as trxcost
  from mytable
)
order by id;

我將您的row id重命名,因為ROW是保留字。

最后一行的結果與您的不同。 我使用了您的公式,但是得到了不同的數字。

Rextester演示: https ://rextester.com/ASXFY4323

請參閱“ SQL窗口函數” ,該函數使您可以訪問結果集中其他行的值。 對於您的情況,您需要告訴我們更多何時停止觀看等條件:

select
    lag(unit,1) over (partition by type order by whatever) 
  * lag(cost,1) over (partition by type order by whatever)
from Trx

但是我仍然想念您如何將事務和減少量相互關聯。 必須有一些您沒有告訴我們的專欄。 如果知道該列(PartNumber?),則可以簡單地對其進行分組和求和。

暫無
暫無

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

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