SQL获取在不同日期的语句帐户中支付的金额

时间:2017-05-28 08:55:16

标签: sql sql-server

我有这个架构

物品

| ItemId | Name  | Price |
|--------|-------|-------|
|   1    |  Item1|  5.00 |
|   2    |  Item2|  2.00 |

OrderHeader

| OrderId| OrderNum| OrderDate  |
|--------|---------|------------|
|   1    | ORD1    | 2017-05-10 |
|   2    | ORD2    | 2017-05-12 |

订单明细

|OrderId| ItemId |  Total |
--------|--------|---------
|   1   |      1 |     3  |
|   2   |      1 |     2  |

我怎样才能得到这个结果:

|ItemId | OrderId   |  Paid  | Debt |
--------|-----------|----------------
|   1   | 1         |     3  |   2  |
|   1   | 2         |     5  |   0  |

在结果集中,已付款列必须包含先前付款的总额,再加上新付款。

我如何使用Common表表达式来解决这个问题?

1 个答案:

答案 0 :(得分:0)

这,你应该提供给我们:

  DECLARE @Item TABLE (Id int, [Name] varchar(15), Price int)
  DECLARE @OrderDetails TABLE (OrderId int, ItemId int, Total int)
  INSERT INTO @ITEM VALUES (1, 'ITEM1', 5), (2, 'ITEM2', 2)
  INSERT INTO @OrderDetails VALUES (1, 1, 3), (2, 1, 2)

这似乎有效,我认为它还有改进的余地:

SELECT OrderId, ItemId, [SUM1], R.Price - [SUM1]
FROM @OrderDetails AS A
LEFT JOIN @Item AS R ON A.ItemId = R.Id
OUTER APPLY (
    SELECT SUM(SUB1.TOTAL) AS [SUM1]
    FROM @OrderDetails AS SUB1
    WHERE SUB1.ItemId = A.ItemId AND SUB1.OrderId <= A.OrderId
) AS B