patternsqlMajor
What are the SQL Server 2012 versions of FIRST() and LAST()?
Viewed 0 times
lastthe2012whataresqlandfirstversionsserver
Problem
I have a table with a
I want to obtain
I've tried to use the below command in SQL Server 2012, however
What is the syntax for this command in SQL Server?
value column. I want to calculate the last row minus the first row, as shown here:id value
1 10
2 45
3 65
4 95
. .
. .
. .
500 200I want to obtain
200 - 10 = 190I've tried to use the below command in SQL Server 2012, however
LAST and FIRST don't work.SELECT LAST(Value) - FIRST(Value) FROM Counter;What is the syntax for this command in SQL Server?
Solution
You were close -
So, if you are 2012 or better (or Azure SQL Database), here's one way to get your answer:
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;Code Snippets
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;Context
StackExchange Database Administrators Q#123327, answer score: 21
Revisions (0)
No revisions yet.