I have two tables as shown below
The master Table
ID keyword_tags
----------- ---------------------------------------------
10932 international foo data
and a child table(join clause on id = fk_id)
fk_id date_value observ_value
----------- ----------------------- ----------------------
10932 2009-01-01 00:00:00.000 331.888888888
10932 2008-06-01 00:00:00.000 301.888888888
10932 2008-01-01 00:00:00.000 321.777777777
10932 2007-01-01 00:00:00.000 288.449066162
10932 2006-01-01 00:00:00.000 259.789733887
Output required is
ID keyword_tags Latest_Value Latest_Change Annual_Change
------ ---------------------- ------------- ------------- ---------------
10932 international foo data 331.888888888 30.000000000 10.111111111
where
Latest_Change = observ_value(of most recent date_value) - observ_value(of next most recent date_value)
Annual_Change = observ_value(of most recent date_value) - observ_value(of recent date_value - 1 year)
How do i achieve this using sql-server?
This should work:
I create the tables as
Let’s insert some data:
Now for the interesting part:
Calculating your Latest_Change and Annual_Change from these is left as an exercise for the reader.