【问题标题】:Moving Average calculation in SQL ServerSQL Server 中的移动平均计算
【发布时间】:2021-03-06 00:23:37
【问题描述】:
CREATE TABLE TmpMAVG 
(
    TransID int identity(1,1) not null, 
    Quantity INT not null, 
    Price money null, 
    Amount money null,
    SortId int not null,
    NewAmount Money null
);

INSERT INTO TmpMAVG (Quantity,Price, Amount, SortId)            
    SELECT 500, 12, 0,1
    UNION ALL SELECT 500, 10, 0,2
    UNION ALL SELECT -100, 0, 0,3
    UNION ALL SELECT -200, 0, 0,4
    UNION ALL SELECT -300, 0, 0,5
    UNION ALL SELECT 800, 15, 0,6
    UNION ALL SELECT -900, 0, 0,7
    UNION ALL SELECT -300, 0, 0,8
    UNION ALL SELECT -500, 0, 0,9
  
UPDATE TmpMavg 
SET Amount = Price * Quantity 
WHERE Quantity > 0

计算预期输出黄色:

如果数量是正数,那么 金额 = 价格 * 数量 别的 金额=(之前所有交易金额之和)/(之前所有交易数量之和)*数量

enter image description here

我尝试了以下查询。但没有运气

UPDATE T1 
SET T1.Amount = (SELECT SUM(Amount)/SUM(Quantity) 
                 FROM TmpMavg 
                 WHERE SortId < T1.SortId) * T1.Quantity
FROM TmpMavg T1 
WHERE T1.Quantity < 0

【问题讨论】:

    标签: sql sql-server sql-update subquery window-functions


    【解决方案1】:

    excel公式的直接翻译是:

    select t.*,
        1.0 * (amount - sum(amount) over(order by transid))
        / nullif(quantity - sum(quantity) over(order by transid), 0)
        * quantity as result
    from TmpMAVG t
    

    【讨论】:

    • 感谢您的回复。如果数量为正,则金额 = 价格 * 数量 否则金额 =(所有先前交易金额之和)/(所有先前交易数量之和)* 数量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    相关资源
    最近更新 更多