使用子選擇了每天的手越來越量的簡化版本。
一個好的/快速的解決方案,如果你沒有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