What are the SQL Server 2012 versions of FIRST() and LAST()?
You were close - FIRST
and LAST
are from Access; in SQL Server (starting with SQL Server 2012) they are FIRST_VALUE()
and LAST_VALUE()
.
So, if you are 2012 or better (or Azure SQL Database), here's one way to get your answer:
CREATE TABLE #fl
(
IdentityColumn INT IDENTITY,
Value INT
);
INSERT #fl(Value) SELECT 10;
INSERT #fl(Value) SELECT 45;
INSERT #fl(Value) SELECT 65;
INSERT #fl(Value) SELECT 95;
INSERT #fl(Value) SELECT 200;
SELECT TOP (1) LAST_VALUE(Value) OVER (ORDER BY IdentityColumn)
- FIRST_VALUE(Value) OVER (ORDER BY IdentityColumn)
FROM #fl
ORDER BY IdentityColumn DESC;
GO
DROP TABLE #fl;
One more way (that works in older versions as well):
SELECT
result = (SELECT TOP (1) value FROM counter ORDER BY id DESC)
- (SELECT TOP (1) value FROM counter ORDER BY id ASC) ;