Last_Value返回多条记录

时间:2017-12-14 07:50:27

标签: sql sql-server performance sql-server-2016

我有一张表(SROEnquiry),如下面的快照中所列: Data.jpg

我正在使用Last_Value()来获取桌面上每个StudentNumberstudent的最后一个条目。使用StudentNumber'Y1293926'作为示例。

脚本如下:

SELECT DISTINCT(StudentNumber),
       LAST_VALUE(Arrears) OVER 
       (PARTITION BY StudentNumber ORDER BY RecordID) AS LastValue  
FROM SROEnquiry 
WHERE StudentNumber = 'Y1293926'

结果如下:

enter image description here

预期结果是:

StudentNumber   LastValue
Y1293926        0.00

脚本有什么问题,它带回4个值而不是只有一个?

3 个答案:

答案 0 :(得分:1)

LAST VALUE返回OVER子句创建的窗口的最后一个值。在RecordID按顺序排列记录时窗口会扩展,因此LAST VALUE每次都会获取不同的值。

此外,DISTINCT适用于SELECT子句的两个字段。因此,您为LAST VALUE返回的每个值获得一条记录。

为什么不使用:

SELECT TOP 1 StudentNumber, Arrears AS LastValue  
FROM SROEnquiry 
WHERE StudentNumber = 'Y1293926'
ORDER BY RecordID DESC

答案 1 :(得分:1)

您需要使用LAST_VALUE指定正确的框架:

SELECT DISTINCT
    StudentNumber,
    LAST_VALUE(Arrears) OVER (PARTITION BY StudentNumber ORDER BY RecordID
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS LastValue  
FROM SROEnquiry 
WHERE StudentNumber = 'Y1293926'

答案 2 :(得分:0)

SELECT DISTINCT(StudentNumber),
       LAST_VALUE(Arrears) OVER 
       (PARTITION BY StudentNumber ORDER BY StudentNumber) AS LastValue  
FROM SROEnquiry 
WHERE StudentNumber = 'Y1293926'