SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query Dilema
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

QueryUser777
Starting Member

USA
3 Posts

Posted - 10/10/2012 :  15:44:01  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 10/10/2012 :  16:01:52  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000