SQL Server特殊运行总查询

时间:2016-03-09 09:55:25

标签: sql-server sql-server-2014 running-total

我使用SQL Server 2014并且想要运行总计。我需要运行总计来计算QuantityUnitPricePrice

UnitPricePrice相关联且与Condition列相关。我不能有两个相关的SUM Over

以下查询是关于我的问题的想法 - 我该怎么做?

提前致谢。

SELECT  
    *,
    SUM(InQuantity - r.OutQuantity) OVER (PARTITION BY r.SalesCompanyId 
                                          ORDER BY r.Date) AS RunningTotalQuantity,
    CASE 
       WHEN Condition = 1 
         THEN LAG(RunningUnitPrice) OVER(PARTITION BY r.SalesCompanyId ORDER BY r.Date) 
         ELSE RunningTotalPrice / RunningTotalQuantity 
    END AS RunningUnitPrice,
    SUM(CASE 
           WHEN Condition = 1 
             THEN (InQuantity - OutQuantity) * RunningUnitPrice
             ELSE InPrice - r.OutPrice
        END) OVER (PARTITION BY r.SalesCompanyId ORDER BY r.Date) AS RunningTotalPrice,
    SUM(InQuantity - r.OutQuantity) OVER (PARTITION BY r.SalesCompanyId ORDER BY r.Date) AS RunningPrice
FROM 
    Inventory

在上面的查询中,我使用RunningTotalPrice来计算RunningUnitPrice并使用RunningUnitPrice来计算RunningTotalPrice

0 个答案:

没有答案