Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE
? Here is a way to get the last value.
select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl
Is it possible to modify it to get second last value?
Update. I am familiar with different ways of getting the last but one value mentioned ie here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.
SELECT
*
FROM
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY [Category]
ORDER BY [MyValue] DESC) AS ordinal
FROM
tbl
)
ordered_tbl
WHERE
ordinal = 2
you can also use OFFSET FETCH function to get second last row.
CREATE TABLE Cinema
([CinemaID] int, [Name] varchar(7))
;
INSERT INTO Cinema
([CinemaID], [Name])
VALUES
(1, 'Odeon'),
(2, 'Mercury'),
(3, 'Apollo'),
(4, 'Venus')
;
SELECT c.*
FROM dbo.Cinema AS c
ORDER BY CinemaID DESC
OFFSET 1 ROW
FETCH FIRST 1 ROW ONLY ;
OK, I have found it. The function LAG
does the job in year 2017. I do not know if it is most performant but it is good enough as simplicity counts.
[MyVal_Last] = LAG([MyValue],1) OVER (PARTITION BY [Category] ORDER BY [MyValue] ASC)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.