如何查询从 table 中删除相同的数据?
How to query for delete the same data out of the table?
我想删除它以使输出看起来像这样。在一组中应该只有 1 user_id.
select distinct group_id, user_id, count(*)
from pin_users
where group_id in (select group_id from pin_users)
group by group_id, user_id
having count(*) > 1
我得到了所有 user_id、group_id 并计数超过 1,但我不知道如何删除重复项,只剩下 1。
Ps。我的英语可能不完美,如有错误请原谅
如果是sql-server
,试试这个:
-- mockup data
declare @Raw table (
id nvarchar(max),
group_id nvarchar(max),
user_id nvarchar(max)
)
insert into @Raw values ('p001', 'aaa', 'ava001'), ('p002', 'aaa', 'ava001'), ('p003', 'bbb', 'ava001'), ('p004', 'bbb', 'ava001');
-- check this query
with A as (
select id, ROW_NUMBER() over(partition by group_id, user_id order by id) as RN
from @Raw)
delete from @Raw where id in (select id from A where A.RN > 1)
-- verify table
select * from @Raw
例如,sql服务器应该是这样的
delete u1
from pin_users u1
join (
select min(id) id, group_id, user_id
from pin_users
group by group_id, user_id
) u2
on u1.group_id = u2.group_id
and u1.user_id = u2.user_id
and u1.id <> u2.id
进行子查询以获取用户和组的任意组合的最小 ID 列表。然后删除所有其他内容。
DELETE FROM pin_users WHERE id NOT IN (
SELECT min(id) as id
FROM pin_users
GROUP BY group_id, user_id
)
我想删除它以使输出看起来像这样。在一组中应该只有 1 user_id.
select distinct group_id, user_id, count(*)
from pin_users
where group_id in (select group_id from pin_users)
group by group_id, user_id
having count(*) > 1
我得到了所有 user_id、group_id 并计数超过 1,但我不知道如何删除重复项,只剩下 1。
Ps。我的英语可能不完美,如有错误请原谅
如果是sql-server
,试试这个:
-- mockup data
declare @Raw table (
id nvarchar(max),
group_id nvarchar(max),
user_id nvarchar(max)
)
insert into @Raw values ('p001', 'aaa', 'ava001'), ('p002', 'aaa', 'ava001'), ('p003', 'bbb', 'ava001'), ('p004', 'bbb', 'ava001');
-- check this query
with A as (
select id, ROW_NUMBER() over(partition by group_id, user_id order by id) as RN
from @Raw)
delete from @Raw where id in (select id from A where A.RN > 1)
-- verify table
select * from @Raw
例如,sql服务器应该是这样的
delete u1
from pin_users u1
join (
select min(id) id, group_id, user_id
from pin_users
group by group_id, user_id
) u2
on u1.group_id = u2.group_id
and u1.user_id = u2.user_id
and u1.id <> u2.id
进行子查询以获取用户和组的任意组合的最小 ID 列表。然后删除所有其他内容。
DELETE FROM pin_users WHERE id NOT IN (
SELECT min(id) as id
FROM pin_users
GROUP BY group_id, user_id
)