从组中排除最小值

时间:2018-10-04 13:07:30

标签: sql sql-server group-by aggregate

我有表格MyTable(编号,位置编号,用户名,日期,排名)

我需要从此表中删除重复项,但左行带有最小ID

select min(cr.id)
from MyTable mt
group by mt.LocationId, mt.UserName, mt.Date, mt.Rank
having count(mt.id) > 1

这是从组中选择最小值的查询...但是不知道如何从重复项中排除它们

select mt.LocationId, mt.UserName, mt.Date, mt.Rank
from MyTable mt
group by mt.LocationId, mt.UserName, mt.Date, mt.Rank
having count(mt.id) > 1

4 个答案:

答案 0 :(得分:3)

您可以使用CTEROW_NUMBER() ROW_NUMBER() OVER ()函数正在查找具有与重复列相同值的行。此列组合的首次出现被分配为rn为1,下一个为2、3,依此类推。 按Id升序排列,最小将为rn = 1,因此删除where rn > 1,删除重复项并保留ID最小的行。

with cte as (
    select
        *
        ,rn = ROW_NUMBER() over (PARTITION BY LocationId, UserName, Date, Rank order by id asc)
    from MyTable 
)
delete from cte where rn > 1

答案 1 :(得分:0)

我会使用row_number()函数:

delete mt
from (select mt.*,
             row_number() over (partition by mt.LocationId, mt.UserName, mt.Date, mt.Rank order by mt.id) as seq
      from MyTable mt
     ) mt
where seq > 1;

答案 2 :(得分:0)

您可以使用row_number窗口功能

with t1 as
(
select * , 
row_number() over(partition by mt.LocationId, mt.UserName, mt.Date, mt.Rank order by Id) as rn from MyTable mt
) delete from t1 where t1.rn!=1

答案 3 :(得分:0)

使用row_number()

Base