使用子选择了每天的手越来越量的简化版本。
一个好的/快速的解决方案,如果你没有100k的交易和/或一个体面的SQL框。
借口凌乱的SQL(午餐编码:P)
CREATE TABLE #transactions (ID INT, DTE DATETIME, PROD VARCHAR(25), QTY INT)
CREATE TABLE #products (ID VARCHAR(25))
CREATE TABLE #dates (DTE DATETIME)
-- create some dates - you would do this dynamically
INSERT INTO #dates values (convert(datetime, '01/01/2011', 103))
INSERT INTO #dates values (convert(datetime, '02/01/2011', 103))
INSERT INTO #dates values (convert(datetime, '03/01/2011', 103))
-- create some products - you would get these from where-ever they live
INSERT INTO #products values ('A')
INSERT INTO #products values ('B')
-- create some transactions - you would get these from where-ever they live
INSERT INTO #transactions values (1, convert(datetime, '01/01/2011', 103), 'A', 25)
INSERT INTO #transactions values (2, convert(datetime, '01/01/2011', 103), 'A', -5)
INSERT INTO #transactions values (3, convert(datetime, '02/01/2011', 103), 'A', 60)
INSERT INTO #transactions values (4, convert(datetime, '02/01/2011', 103), 'A', -15)
INSERT INTO #transactions values (5, convert(datetime, '03/01/2011', 103), 'A', 100)
INSERT INTO #transactions values (6, convert(datetime, '03/01/2011', 103), 'A', -20)
INSERT INTO #transactions values (7, convert(datetime, '01/01/2011', 103), 'B', 10)
INSERT INTO #transactions values (8, convert(datetime, '01/01/2011', 103), 'B', 5)
INSERT INTO #transactions values (9, convert(datetime, '02/01/2011', 103), 'B', -30)
INSERT INTO #transactions values (1, convert(datetime, '02/01/2011', 103), 'B', 50)
INSERT INTO #transactions values (11, convert(datetime, '03/01/2011', 103), 'B', 10)
INSERT INTO #transactions values (12, convert(datetime, '03/01/2011', 103), 'B', 200)
-- Join dates and transactions - Do a sub select from 'begining of time' to get qty on hand per day
SELECT CONVERT(VARCHAR(25), a.DTE, 103), b.id, (SELECT sum(qty) from #transactions c where b.id = c.prod and c.DTE <= a.DTE)
FROM #dates a, #products b
-- One benefit to this approach means you can genereate qty_on_hand per days were no transactions have occured (if you needed this)
DROP TABLE #transactions
DROP TABLE #products
DROP TABLE #dates
你如何设置在从输入输出?输入中的“12/31/2010”在哪里? – Quassnoi 2011-04-28 11:39:55
@Quassnoi:我猜目前'Items'表有“运行余额”。然后,他从过去的任意一天(开始日期)开始,从“01/01/2011”到现在(或另一个任意日期),都需要“历史”。 '12/31/2010'是“开始日期”的前一天。 – 2011-04-28 11:49:07
ypercude是正确的。物料表在当前日期中具有库存量(现在仓库中的数量)。我需要按天清点当天的数量。 – awilinsk 2011-04-28 11:53:41