在SQL中仅从表中获取最新ID的最佳方法是什么

时间:2018-12-10 22:58:59

标签: sql-server tsql

我试图在存储约会历史记录的表中每个约会编号仅获取一行。它可以在几行上正常工作,但是会变慢?这是执行这种检查的最佳方法,而我只是缺少一些索引,还是有更好的方法?

DECLARE @temptable TABLE
    (
        id INT PRIMARY KEY NOT NULL
      , ApptNumber INT NOT NULL
      , ApptDate DATE NOT NULL
      , Notes VARCHAR(50) NULL
    )

INSERT INTO @temptable VALUES (1,1,'01-DEC-2018','First Appointment')
INSERT INTO @temptable VALUES (2,1,'01-DEC-2018','')
INSERT INTO @temptable VALUES (3,1,'01-DEC-2018','Rescheduled')
INSERT INTO @temptable VALUES (4,2,'02-DEC-2018','Second Appointment')
INSERT INTO @temptable VALUES (5,2,'02-DEC-2018','Cancelled')
INSERT INTO @temptable VALUES (6,3,'03-DEC-2018','Third Appointment')
INSERT INTO @temptable VALUES (7,4,'04-DEC-2018','Fourth Appointment')

SELECT * FROM @temptable
SELECT MAX(id) FROM @temptable GROUP BY ApptNumber

SELECT tt.* FROM @temptable tt
INNER JOIN  (SELECT MAX(id) [Id] FROM @temptable GROUP BY ApptNumber) appts ON appts.Id = tt.id

4 个答案:

答案 0 :(得分:1)

解决方案1:

select * from (
    SELECT f1.*, row_number() over(partition by ApptNumber order by id desc ) rang FROM @temptable f1
) tmp where rang=1

答案 1 :(得分:0)

解决方案2:

with tmp as (
select ApptNumber, max(ID) MaxID
from @temptable
group by ApptNumber
)
select f1.* from @temptable f1 inner join tmp f2 on f1.ID=f2.MaxID

答案 2 :(得分:0)

解决方案3:

select distinct f3.* from @temptable f1 
cross apply
(
 select top 1 * from @temptable f2
 where f1.ApptNumber=f2.ApptNumber
 order by f2.ID desc

) f3

答案 3 :(得分:0)

窗口功能

SELECT tt.* 
FROM (
  SELECT *, row_number() over (partition by ApptNumber order by id desc) as rn 
) tt
where tt.rn = 1