Mathematical SQL Query

I think Doug’s (Duffanator) point is that it’s not going to be a simple query. :wink: Subqueries are necessary to grab an aggregate (SUM, AVG, etc.) and go back and grab the second to last value.

Here’s a table I created (SQL Server 2000) called Table1

[code]________________
| ndx | sample |

| 1 | 123.4 |

| 2 | 234.5 |

| 3 | 345.6 |

| 4 | 432.1 |
----------------[/code]

To get the average of the last two values (that’s what i/2[/i]) really is:

SELECT AVG(sample) ## SUM(sample)/2 works also ## FROM (SELECT TOP 2 * FROM Table1 ORDER BY ndx DESC) t

To get the second to last value

SELECT TOP 1 sample FROM (SELECT TOP 2 * FROM Table1 ORDER BY ndx DESC) t ORDER BY ndx

So that’s two queries. Now you need a third one to put it all together subtracting the second one (and get the absolute value-- I didn’t forget! :laughing: ).

SELECT ABS ((SELECT AVG(sample) FROM (SELECT TOP 2 * FROM Table1 ORDER BY ndx DESC) t) - (SELECT TOP 1 sample AS Expr1 FROM (SELECT TOP 2 * FROM Table1 ORDER BY ndx DESC) t ORDER BY ndx)

Sometimes the trick is knowing when to use SQL or when it’s better to write a script:

[code]query=“SELECT TOP 2 * FROM Table1 ORDER BY ndx DESC”
result=system.db.runQuery(query, “database”)
b=result[0][“sample”] #remember, they came in reverse order
a=result[1][“sample”]

print abs((a+b)/2-a)[/code]


Hope this helps!