2013-02-18 146 views
0

我有一張桌子,在這裏我想更新今天的收盤餘額應該顯示爲tomarrows開盤餘額,如果任何更新的closingbalance發生在特定的日期然後從該日期到當前日期期初餘額應該得到更新,這裏是我想要的樣本輸出如下; openingbalance(今天)=年末數(昨天)類似於跑臺概念

date  opening_balance closing_balance accountformatid daybooktype 
18-02-2013 12000    15000   1    240 
19-02-2013 15000    14000   1    240 
20-02-2013 14000    13000   1    240 
21-02-2013 13000    10000   1    240 
22-02-2013 10000    5000   1    240 
23-02-2013 50000    1500   1    240 

怎麼會這樣來達到的PLZ幫我

+0

不清楚。澄清你的問題。 – 2013-02-18 11:47:38

回答

0

試試這個:

DECLARE @t TABLE (date DATETIME,  opening_balance INT, closing_balance INT,accountformatid INT,daybooktype INT) 

INSERT @t 
SELECT CONVERT(DATE, a, 105), b,c,d,e 
FROM (VALUES 
('18-02-2013',12000 ,15000 ,1,240), 
('19-02-2013',15000 ,14000 ,1,240), 
('20-02-2013',14000 ,13000 ,1,240), 
('21-02-2013',13000 ,10000 ,1,240), 
('22-02-2013',10000 ,5000 ,1,240), 
('23-02-2013',50000 ,1500 ,1,240) 
) tbl(a,b,c,d,e) 

SELECT t1.* 
     , t2.* 
FROM @t t1 
LEFT JOIN 
     @t t2 ON t1.date = DATEADD(DAY, 1, t2.date) 
AND  t1.opening_balance = t2.closing_balance 
WHERE t2.closing_balance IS NULL 
-- this prevents first record to be falsely reported 
AND  t1.date <> (SELECT MIN(date) FROM @t) 

這列出的兩個連續的記錄中沒有第二按日期和餘額對應。