Search code examples
sqlsql-servergroup-bysql-delete

How to delete all rows by group except the first and the last one in SQL Server?


I have data like this

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

I need a query which will delete all rows by group AuthorId if there are more then 2, except the first and the last one.

For example, in the above data, the second row should be deleted, because, for AuthorId = 2, I have 3 rows, but for AuthorId = 3, nothing will be deleted


Solution

  • Row_number() twice and delete non-terminals

    delete t
    from (
       select *,
          row_number() over(partition by [AuthorId]  order by [Id]) n1,
          row_number() over(partition by [AuthorId]  order by [Id] desc) n2
       from tablename
    ) t
    where n1 > 1 and n2 > 1