Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query Dilema

Author  Topic 

QueryUser777
Starting Member

3 Posts

Posted - 2012-10-10 : 15:44:01
Hi all,
First, please forgive my ignorance and I thank you beforehand for your patience. I need to figure out a way to get the following results. I have a query with the query results below:

Date StartVol EndVol Diff
08/01 100 15 85
08/02 125 27 98
08/03 107 42 65

What i need is to add a field that will calculate the difference between the day's StartVol - (previous day's EndVol). So for exp the query should look like below:

Date StartVol EndVol Diff Import(new field)
08/01 100 15 85 0
08/02 125 27 98 73(125-15)
08/03 107 42 65 80(107-27)

Any information or direction on how to get the "Import" field is greatly appreciated. Thanks.

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2012-10-10 : 16:01:52
Assuming your [date] column is a DATETIME datatype then this would work. Looks like your sample data is wrong? 73(125-15). Shouldn't that be 110?

declare @yourTable table (date datetime, startVol int, endVol int, diff int)
insert @yourTable
select '08/01/2012', 100, 15, 85 union all
select '08/02/2012', 125, 27, 98 union all
select '08/03/2012', 107, 42, 65

;with cte
as
(
select date
,startVol
,endVol
,diff
,row_number() over (order by date) as rn
from @yourTable
)
select a.*, isNull(a.startVol - b.endVol,0) as [import(New Field)]
from cte a
left outer join cte b on b.rn = a.rn-1

OUTPUT:
date startVol endVol diff rn import(New Field)
----------------------- ----------- ----------- ----------- -------------------- -----------------
2012-08-01 00:00:00.000 100 15 85 1 0
2012-08-02 00:00:00.000 125 27 98 2 110
2012-08-03 00:00:00.000 107 42 65 3 80



Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -