Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is LAST_VALUE() not working in SQL Server?

Tags:

sql

sql-server

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?

like image 282
JJ. Avatar asked Aug 07 '15 18:08

JJ.


People also ask

What is Last_value in SQL?

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.

How to get LAST VALUE in SQL?

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.

How does lag work in SQL?

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.

How does partition by work in SQL?

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.


1 Answers

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
like image 168
shawnt00 Avatar answered Oct 11 '22 12:10

shawnt00