How to write a query to remove duplicates in a table?

Given a table similar to this one called VehicleUser:

VehicleUserId | VehicleId | UserId
1 | 1001 | 2
2 | 1001 | 2
3 | 1001 | 2
4 1001 | 3
5 & ​​nbsp; | 1001 | 3
6 | 1001 | 3

How to write a query that can remove duplicates? lines 2 and 3 are identical to line 1, with the exception of another VehicleUserId, and lines 5 and 6 are identical to 4, with the exception of another VehicleUserId.

+3
source share
4 answers
;with cte as (
select row_number() over 
    (partition by VehicleId, UserId order by VehicleUserId) as rn
from VehicleUser)
delete from cte
where rn > 1;
+6
source

exists, :

delete  v1
from    VehicleUser v1
where   exists
        (
        select  *
        from    VehicleUser v2
        where   v1.VehicleId = v2.VehicleId
                and v1.UserId = v2.UserId
                and v1.VehicleUserId > v2.VehicleUserId
        )

, , , delete select:

select  *
from   VehicleUser v1
where  exists
       (
       ...

, , .

+5

:

select vehicleid, userid, min(vehicleuserid) as min_id
from vehicleuser
group by vehicleid, userid

, -, , , , VehicleUser VehicleUser, .

.

+3

, .

, , , , VehicleUserId.

select VehicleId, UserId
from VehicleUser
group by VehicleId, UserId
having count(*) > 1

VehicleId/UserId, .

+1

Source: https://habr.com/ru/post/1787740/


All Articles