我使用SQL Server 2014并且想要运行总计。我需要运行总计来计算Quantity
,UnitPrice
和Price
。
UnitPrice
和Price
相关联且与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
。