Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Kapital123
Starting Member
31 Posts |
Posted - 2013-01-08 : 01:17:11
|
Hi all,I have attempted all sorts of approaches to my latest dilemma to no avail. In essence what I want to do is subtract the current value from the previous available value, grouping by the company code. A sample of my data is as follows:3 Fields + Change ColumnCompany_Code Date Score Change(What I Want!!)ABC 25/05/2012 86 0ABC 28/08/2012 86 0ABC 01/01/2013 66 -20XYZ 25/05/2012 89 0XYZ 28/08/2012 95 +6XYZ 01/01/2013 81 -14. . .. . .. . .Anyone have any ideas on the most optimal SQL Code in achieving this ? |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-01-08 : 01:20:28
|
[code]SELECT t.*,COALESCE(t.Score - p.Score,0) AS ChangeFROM table tOUTER APPLY (SELECT TOP 1 Score FROM table WHERE Company_Code = t.Company_Code AND [Date] < t.[Date] ORDER BY [Date] DESC)p[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
Kapital123
Starting Member
31 Posts |
Posted - 2013-01-08 : 04:07:12
|
Thanks Visakh16, I will give this a go |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-01-08 : 04:17:52
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
|
|
|