SQL Server中其他表的累计累计期

时间:2017-04-09 08:28:54

标签: sql sql-server

我有下面的表格交易

O(1)

我有桌子交付日期

@import url('style.css');

我想要这样的结果

Product Qty    Date         
A       100    01/01/2017
A       100    03/01/2017
A       200    04/01/2017 
A       100    05/01/2017
B       100    07/01/2017
B        50    08/01/2017
B       200    10/01/2017
B       100    17/01/2017
C       100    20/01/2017
C       300    21/01/2017
C       150    24/01/2017

我很困惑如何创建查询以获得该结果。 你能帮帮我吗?

由于

1 个答案:

答案 0 :(得分:0)

你可以试试这个

DECLARE @Transaction AS TABLE (Product varchar(10), Qty int, [Date] date)
INSERT INTO @Transaction
VALUES ('A', 100, '2017-01-01'), ('A', 100, '2017-01-03'), ('A', 200, '2017-01-04'), ('A', 100, '2017-01-05'),
('B', 100, '2017-01-07'),('B', 50, '2017-01-08'),('B', 200, '2017-01-10'),('B', 100, '2017-01-17'),
('C', 100, '2017-01-20'),('C', 300, '2017-01-21'),('C', 150, '2017-01-24')


DECLARE @Delivery AS TABLE (startdate date, enddate date, deliverydate date)
INSERT INTO @Delivery VALUES ('2017-01-01', '2017-01-15', '2017-01-17'), ('2017-01-16', '2017-01-31', '2017-02-04')


SELECT t.Product,SUM(t.Qty) AS TotalQty , d.DeliveryDate  
FROM @Transaction t
INNER JOIN @Delivery d ON t.[Date] >= d.startdate AND t.[Date] <= d.enddate
GROUP BY t.Product,d.DeliveryDate

演示链接:Rextester