Here's the data I have (note that this is for only one entity id / employee id, there will be multiple. One entity ID can have multiple employee IDs under it):
SELECT EntityId,
EmployeeId,
PayPeriodStart,
IsFullTime
FROM dbo.Payroll
WHERE EmployeeId = 316691
AND PayPeriodStart <= '12/31/2014'
AND PayPeriodEnd >= '1/1/2014';
I want to grab the LAST "IsFullTime" value FOR EACH EntityID & EmployeeID combo.
I tried doing this:
SELECT EntityId,
EmployeeId,
LAST_VALUE(IsFullTime) OVER (PARTITION BY EntityId, EmployeeId ORDER BY EntityId, EmployeeId, PayPeriodStart) AS LastIsFullTimeValue
FROM dbo.Payroll
WHERE EmployeeId = 316691
AND PayPeriodStart <= '12/31/2014'
AND PayPeriodEnd >= '1/1/2014';
But I'm getting this:
The query should return only ONE row FOR EACH EntityID / EmployeeID.
What am I doing wrong?
LAST_VALUE is an analytic function. It returns the last value in an ordered set of values. If the last value in the set is null, then the function returns NULL unless you specify IGNORE NULLS . This setting is useful for data densification.
We could use LAST_VALUE() in SQL Server to find the last value from any table. LAST_VALUE() function used in SQL server is a type of window function that results the last value in an ordered partition of the given data set.
LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.
Partition By: This divides the rows or query result set into small partitions. Order By: This arranges the rows in ascending or descending order for the partition window. The default order is ascending. Row or Range: You can further limit the rows in a partition by specifying the start and endpoints.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With