我正在尝试获取一组值(分区)中的最后一个值,但遇到了一些麻烦。在下面的示例中,您可以看到我正在使用的示例数据集。 MAX() 不起作用,因为这里的“最后一个”是分区 (ID) 中最后一个日期的日期。我在下面的查询中注释掉了 LAST_VALUE ,但这似乎也不起作用......不确定我做错了什么。我想要的是这样的结果数据集:
create table #Example (ID int, [Date] datetime, Rating tinyint)
insert into #Example (ID, [Date], Rating)
values
(5227, '2021-01-11 19:21:39.107', 1)
,(128, '2020-06-16 17:32:15.653', 5)
,(128, '2020-06-23 11:35:16.570', 1)
,(2038, '2020-09-14 13:13:48.253', 2)
,(1268, '2020-07-30 16:05:07.950', 0)
,(2398, '2020-09-30 13:51:21.813', 5)
,(2058, '2020-09-14 13:13:48.253', 1)
,(3396, '2020-11-05 12:04:16.043', 5)
,(3396, '2020-12-07 13:23:05.357', 3)
,(3148, '2020-11-05 12:04:16.043', 1)
,(3399, '2020-11-06 12:04:16.043', 2)
,(3399, '2020-12-08 13:23:05.357', 4)
select
exm.ID
, exm.Date
, exm.Rating
--, LAST_VALUE(exm.Rating) over (partition by exm.ID order by exm.Date) as [FinalRating]
from
#Example as exm
drop table #Example
如果您有任何帮助,我将不胜感激!
最佳答案
也许对您的查询稍加修改就会起作用:
create table #Example (ID int, [Date] datetime, Rating tinyint)
insert into #Example (ID, [Date], Rating)
values
(5227, '2021-01-11 19:21:39.107', 1)
,(128, '2020-06-16 17:32:15.653', 5)
,(128, '2020-06-23 11:35:16.570', 1)
,(2038, '2020-09-14 13:13:48.253', 2)
,(1268, '2020-07-30 16:05:07.950', 0)
,(2398, '2020-09-30 13:51:21.813', 5)
,(2058, '2020-09-14 13:13:48.253', 1)
,(3396, '2020-11-05 12:04:16.043', 5)
,(3396, '2020-12-07 13:23:05.357', 3)
,(3148, '2020-11-05 12:04:16.043', 1)
,(3399, '2020-11-06 12:04:16.043', 2)
,(3399, '2020-12-08 13:23:05.357', 4)
select
exm.ID
, exm.Date
, exm.Rating
, last_value(exm.Rating) over (partition by exm.id order by exm.date
rows between current row and unbounded following) as [FinalRating]
from
#Example as exm
order by id, date
关于sql-server - T-SQL 获取给定组的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66000919/