如何按组删除除SQL Server中的第一个和最后一个行以外的所有行?

问题描述 投票:0回答:2

我有这样的数据

Id Name AuthorId 
1  AAA  2
2  BBB  2
3  CCC  2
4  DDD  3
5  EEE  3

我需要一个查询,如果第一个和最后一个除外,则将删除AuthorId组中的所有行(如果多于2,则全部删除)。例如,在上述数据中,应删除第二行,因为对于AuthorId = 2,我有3行,但是对于AuthorId = 3,则不会删除任何内容

sql sql-server group-by sql-delete
2个回答
0
投票

您可以尝试使用最小和最大id的联合,而不是此子查询的结果中的联合

delete from my_table 
where id  NOT  IN  (


    select  min(id) 
    from my_table 
    group by AuthorId 
    union 
    select max(id)
    from my_table 
    group by AuthorId 

)

0
投票

使用EXISTS

delete t
from tablename t
where 
  exists (
    select 1 from tablename
    where authorid = t.authorid and id > t.id
  )
  and
  exists (
    select 1 from tablename
    where authorid = t.authorid and id < t.id
  )

请参见demo。结果:

Id  Name    AuthorId
1   AAA     2
3   CCC     2
4   DDD     3
5   EEE     3
© www.soinside.com 2019 - 2024. All rights reserved.