考虑 SQL 服务器中所有先前的总和,获取行式总和
Get row wise sum considering all the previous sums in SQL Server
考虑到所有先前的总和,尝试获得逐行总和,并得到如下所示的输出。
任何人都可以告诉我我缺少什么吗?
SELECT
ProductId,
ProductName,
ProductAmount As ProductActualAmount,
CASE
WHEN (CASE
WHEN LEAD(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LEAD(ProductAmount) OVER (ORDER BY ProductId)
END) != 0.00 THEN (ProductAmount + CASE
WHEN LAG(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LAG(ProductAmount) OVER (ORDER BY ProductId)
END)
ELSE (CASE
WHEN LEAD(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LEAD(ProductAmount) OVER (ORDER BY ProductId)
END)
END AS SumAmount
FROM ProductSales
输出:
预期输出:
ProductId ProductName ProductActualAmount SumAmount
---------------------------------------------------------
1 Rexona 35.00 35.00
2 Liril 40.00 75.00
3 Dove 45.00 120.00
4 Pears 50.00 170.00
使用 SUM() OVER
将得到您预期的结果:
SELECT ProductId,
ProductName,
ProductAmount AS ProductActualAmount,
SUM(ProductAmount) OVER (ORDER BY ProductId) AS SumAmount
FROM ProductSales
您还可以使用相关子查询作为
SELECT ProductId,
ProductName,
ProductAmount AS ProductActualAmount,
(
SELECT SUM(PS2.ProductAmount)
FROM ProductSales PS2
WHERE PS1.ProductAmount >= PS2.ProductAmount
) SumAmount
FROM ProductSales PS1;
考虑到所有先前的总和,尝试获得逐行总和,并得到如下所示的输出。
任何人都可以告诉我我缺少什么吗?
SELECT
ProductId,
ProductName,
ProductAmount As ProductActualAmount,
CASE
WHEN (CASE
WHEN LEAD(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LEAD(ProductAmount) OVER (ORDER BY ProductId)
END) != 0.00 THEN (ProductAmount + CASE
WHEN LAG(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LAG(ProductAmount) OVER (ORDER BY ProductId)
END)
ELSE (CASE
WHEN LEAD(ProductAmount) OVER (ORDER BY ProductId) IS NULL THEN 0
ELSE LEAD(ProductAmount) OVER (ORDER BY ProductId)
END)
END AS SumAmount
FROM ProductSales
输出:
预期输出:
ProductId ProductName ProductActualAmount SumAmount
---------------------------------------------------------
1 Rexona 35.00 35.00
2 Liril 40.00 75.00
3 Dove 45.00 120.00
4 Pears 50.00 170.00
使用 SUM() OVER
将得到您预期的结果:
SELECT ProductId,
ProductName,
ProductAmount AS ProductActualAmount,
SUM(ProductAmount) OVER (ORDER BY ProductId) AS SumAmount
FROM ProductSales
您还可以使用相关子查询作为
SELECT ProductId,
ProductName,
ProductAmount AS ProductActualAmount,
(
SELECT SUM(PS2.ProductAmount)
FROM ProductSales PS2
WHERE PS1.ProductAmount >= PS2.ProductAmount
) SumAmount
FROM ProductSales PS1;