我有一张表(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'
结果如下:
预期结果是:
StudentNumber LastValue
Y1293926 0.00
脚本有什么问题,它带回4个值而不是只有一个?
答案 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'