Sql server 2012 SQL Server中偏移量限制的替换

Sql server 2012 SQL Server中偏移量限制的替换,sql-server-2012,offset,sql-delete,Sql Server 2012,Offset,Sql Delete,我们有一个DataTemp表,该表按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

我们有一个
DataTemp
表,该表按
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) 
  • sno
    -自动标识
  • id
    -车门代码*
  • N\u th\u记录
    -用于表示记录的
    N
    一次,此表上每个门只需要存储三条*记录。例如,门“a”有新条目(表示第四条记录),然后需要删除门“a”中的第一条

    第四项记录:

    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 
    ) 
    
    注意:

    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) 
    
  • 以三排三门为例。实际上,我们的工作是每12扇门144行
  • 在此删除之前,我们检查了很多业务规则
  • 版本:SQL Server 2012

  • 您可以使用
    行编号

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

    “在这次删除之前,我们检查了很多业务规则。”尽管这是您的
    删除过程中的一项要求,但您还是将其从您的帖子中豁免了吗?您的SQL中也没有
    DELETE
    ;我们错过了吗?@Larnu我没有完全理解你想说的话。但我们的指示是删除特定门的多余记录。您需要比较实际执行计划。请注意,您的
    OFFSET FETCH
    版本适用于单门,
    行号
    正在同时处理所有门,因此我没有时间研究执行计划。这就是为什么我在这么短的时间内寻求帮助。这将在
    触发器中使用。因此,一次处理一个门。将在测试后的白天接受您的答案。谢谢你的支持。