替换 SQL 服务器中的偏移限制

replacement of Offset Limit in SQL Server

我们有 DataTemp table,其中有 desc 顺序的记录。

select * from ( 
select 9,'a',3 union 
select 8,'a',2 union 
select 7,'b',3 union 
select 6,'a',1 union 
select 5,'b',2 union 
select 4,'c',3 union 
select 3,'c',2 union 
select 2,'b',1 union 
select 1,'c',1 
) door (sno,id, N_th_Reocord) 
  1. sno - 自动识别。
  2. id - 大门代码*。
  3. N_th_Record - 用于表示 n 记录。

在这个 table 上,每扇门一次只需要存储三个*记录。例如 Door 'a' 有新条目(意味着第 4 条记录)然后第一个 'a' Door 需要删除。

第 4 条记录:

select * from ( 
select 10,'a',4 union --- new entry 
select 9,'a',3 union 
select 8,'a',2 union 
select 7,'b',3 union 
select 6,'a',1 union -- need to delete
select 5,'b',2 union 
select 4,'c',3 union 
select 3,'c',2 union 
select 2,'b',1 union 
select 1,'c',1 
) door (sno,id, N_th_Reocord) 

我做了以下查询。但我需要最简单的方法来删除该行。因为,我们正在努力减少整个项目的时间消耗。

delete from door where sno = (
 select sno from ( 
  select 10,'a',4 union 
  select 9,'a',3 union 
  select 8,'a',2 union 
  select 7,'b',3 union 
  select 6,'a',1 union 
  select 5,'b',2 union 
  select 4,'c',3 union 
  select 3,'c',2 union 
  select 2,'b',1 union 
  select 1,'c',1 
 ) door (sno,id, N_th_Reocord) 
 where id = 'a' 
 order by sno desc -- For 'DataTemp' *order by* is no needed. 
 offset 3 rows fetch next 1 rows only 
) 

注:

  1. 以三排三门为例。实际上,我们每 12 扇门处理 144 行。
  2. 在此删除之前,我们检查了很多业务规则。
  3. 版本:SQL 服务器 2012

您可以使用 ROW_NUMBER:

WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY id ORDER BY sno DESC) rn FROM t)
DELETE FROM cte WHERE rn > 3;

db<>fiddle demo