类似于运行表的概念

时间:2013-02-18 11:44:59

标签: sql-server-2008

我有一张表,因为我想要更新今天的期末余额应该显示为至少开仓余额,如果对特定日期进行任何更新,那么从该日期到当前日期开仓余额应该更新,这里是我想要的样本输出如下; 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

这怎么可能帮助我

1 个答案:

答案 0 :(得分: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)

这列出了两个后续记录中第二个与日期和余额不对应的记录。