1

考虑到所有先前的总和,尝试逐行求和,并得到如下所示的输出。

谁能告诉我我错过了什么?

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
4

2 回答 2

3

使用SUM() OVER将给出您预期的结果:

SELECT ProductId, 
       ProductName,
       ProductAmount AS ProductActualAmount,
       SUM(ProductAmount) OVER (ORDER BY ProductId) AS SumAmount
FROM ProductSales

db<>fiddle 上的演示

于 2019-08-08T06:43:54.503 回答
1

您还可以将相关子查询用作

SELECT ProductId, 
       ProductName, 
       ProductAmount AS ProductActualAmount,
       (
         SELECT SUM(PS2.ProductAmount)
         FROM ProductSales PS2
         WHERE PS1.ProductAmount >= PS2.ProductAmount 
       ) SumAmount
FROM ProductSales PS1;

演示

于 2019-08-08T07:08:14.727 回答