sql server - SQL calculate growth percent from datatable -


i have following datatable in sql server 2012 db:

date          ticker    price 2015-09-25              10 2015-09-24              9 2015-09-23              8 2015-09-25      b         3 2015-09-24      b         4 2015-09-23      b         5 

and want select following values sql query:

ticker   value        1.25  b       0.6 

where value ticker 10 / 8 (newest date , specific date in example 2015-09-23 , should changeable).

value ticker b 3 / 5.

this have tried:

select distinct ticker,  round( ((select price indicepricehistory ticker = 'a' , eod =  '2015-09-25') / (select price indicepricehistory ticker = 'a' , eod = '2015-09-23')),2) value indicepricehistory 

so @ least need ticker = 'a' relative actual ticker selected.. , eod's (eod = date) variable..

thank in advance.

you can use first_value , last_value first , last prices per tracker, respectively. there on, it's math:

select distinct [tracker],         last_value([price]) on (partition [tracker]                                   order [date]                                  rows between unbounded preceding ,                                               unbounded following) /        first_value([price]) on (partition [tracker]                                    order [date]                                     rows between unbounded preceding ,                                                 unbounded following)        [growth]                                   mytable 

sqlfiddle


Comments