Why is LAST_VALUE() not working in SQL Server?
Try adding ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
I believe the default window for analytic functions that includes an ORDER BY
ends at the current row.
LAST_VALUE(IsFullTime) OVER (
PARTITION BY EntityId, EmployeeId
ORDER BY EntityId, EmployeeId, PayPeriodStart
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS LastIsFullTimeValue
Here's the trick. I use FIRST_VALUE
+ DESC
ordering (instead of LAST_VALUE
+ ASC
ordering). Works. It is the shortest way and it let you avoid dreaded ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.
FIRST_VALUE(IsFullTime) OVER (
PARTITION BY EntityId, EmployeeId
ORDER BY EntityId DESC, EmployeeId DESC, PayPeriodStart DESC
) AS LastIsFullTimeValue
Agreed, it is confusing why LAST_VALUE
is not intuitive and requires so much attention compared to its twin sister FIRST_VALUE
.
I believe you are looking to use ROW_NUMBER()
and the get the last value based on payperiodstart
date:
SELECT t.EntityId
,t.EmployeeId
,t.LastIsFullTimeValue
FROM (
SELECT EntityId
,EmployeeId
,ROW_NUMBER() OVER (
PARTITION BY EntityId
,EmployeeId ORDER BY PayPeriodStart DESC
) AS rn
,LastIsFullTimeValue
FROM dbo.Payroll
WHERE EmployeeId = 316691 -- you could probably put this in your outer query instead
AND PayPeriodStart <= '12/31/2014'
AND PayPeriodEnd >= '1/1/2014'
) t
WHERE t.rn = 1;