sql server 2008 - Calculate diffrences between values from diffrent rows in SQL -


i have table :

month_date account cash  1          2222    5000    2          2222    6000   3          2222    7000  4          2222    10000  2          1111    5000    3          1111    7000   4          1111    8000   

and desired output should :

month_date account cash diff 1          2222    5000   na 2          2222    6000  1000/5000= 0.2 3          2222    7000  1000/6000= 0.16 4          2222    10000 3000/7000 = 0.42 2          1111    5000   na 3          1111    7000  2000/5000= 0.4 4          1111    8000  1000/7000= 0.14 

without calculation of course. not accounts has data month 1, see account 1111 think of ranking them. i'm looking subtract , divide rows on partition of account.

select month_date, account, cash,  rank() on (partition month_date, account) order month_date rnk,  diff =  case when rnk = 1 'na' else ???? 

any suggestions how perform this?

for before sql server 2012

select     m.month_date,     m.account,     m.cash,     diff = x.cash -  m.cash     mytable m     outer apply     (select top 1         *             mytable m2             m.account = m2.account         ,         m.month_date < m2.month_date     order         month_date     ) x 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -