我正在尝试根据时间戳从表中获取最新记录。他是我写的查询:
SELECT DISTINCT
[Year],
[Type],
[Category],
[AnnualCost],
MAX([TimeStamp]) OVER (PARTITION BY [Year], [Type], [Category], [AnnualCost]) AS MaxTimeStamp
FROM
[PromOneSite].[Budgeting].[MISBasePrice]
WHERE
Year = 2016
AND category IN ('Leasing Office Desktop')
AND TimeStamp IS NOT NULL
结果:
Year Type Category AnnualCost MaxTimeStamp
----------------------------------------------------------------------------
2016 Equipment Hardware Location Leasing Office Desktop 750.00 2015-10-14 17:54:09.510
2016 Equipment Hardware Location Leasing Office Desktop 850.00 2015-10-14 17:54:20.630
我得到了这两个不同数量和不同时间戳的记录。我知道这是因为我在查询中添加了不同的内容,它也为我带来了明显的Annualcost。但如果没有明显的差异,我会获得大约30多个重复记录
在这种情况下,如何只获得一条带有最新时间戳的记录。
提前致谢
答案 0 :(得分:1)
select * from
( SELECT [Year]
,[Type]
,[Category]
,[AnnualCost]
,[TimeStamp] as MaxTimeStamp
,row_number() over (partition by [Year], [Type], [Category] order by [TimeStamp] desc ) as rn
FROM [PromOneSite].[Budgeting].[MISBasePrice]
where Year = 2016
and category IN ('Leasing Office Desktop')
and TimeStamp IS Not Null
) tt
where tt.rn = 1
答案 1 :(得分:0)
SELECT top 1 distinct [Year] ,[Type] ,[Category] ,[AnnualCost] ,max([TimeStamp]) over (partition by [Year],[Type],[Category], [AnnualCost] ) as MaxTimeStamp FROM [PromOneSite].[Budgeting].[MISBasePrice] where Year = 2016 and category IN ('Leasing Office Desktop') order by [TimeStamp] DESC