0

I have a table with the below format:

ID  curr    Date                    Bid     Ask
1   AUD/NZD 20090501 00:00:00.833   1.2866  1.28733
2   AUD/NZD 20090501 01:01:01.582   1.28667 1.2874
3   AUD/NZD 20090501 02:01:01.582   1.28667 1.28747

Now I need to select the change of Bid and Ask column and store into a different table...The result should be like the following

Bid Change  Ask Change  

0.0000700   0.0000700   
0.0000000   0.0000700   


select 
    t1.id, 
    t1.curr, 
    t1.date,
    t1.bid, 
    t1.bid - t2.bid [Bid Change],  
    t1.ask, 
    t1.ask - t2.ask [Ask Change]

from tbltest t1
left join tbltest t2 on t1.ID = t2.ID + 1
order by date

This query returns everything correct except the format of Bid Change and Ask Change...like the following

 BID Change            ASK CHANGE
7.00000000000145E-05  7.00000000000145E-05

Am really clueless on what to do with this situation...any little help will work.

Thanks in advance!

Joyeeta Sinharay
  • 185
  • 2
  • 3
  • 14

1 Answers1

1

It doesn't seem necessary to me to store them in a different table, you can just calculate them on the fly using APPLY, this way any changes to the underlying data will not cause your change data to be stale:

SELECT  T.*,
        BidChange = t.Bid - prev.Bid,
        AskChange = t.Ask - prev.Ask
FROM    T
        OUTER APPLY
        (   SELECT  TOP 1 T2.Bid, T2.Ask
            FROM    T AS T2
            WHERE   T2.Curr = T.Curr
            AND     T2.Date < T.Date
            ORDER BY T2.Date DESC
        ) AS prev;

If this is something you will need regularly then you may want to consider a view, rather than storing it in a table.


enter image description here

GarethD
  • 68,045
  • 10
  • 83
  • 123