求一 SQL 语句,消除相同数据,复制到同一表(急)

yeeyee 2005-08-17 09:28:20
注:
1、Name,GroupId 在数据表中确定一条记录
2、希望用 Insert Into Select 实现吧。

表名:Test

//源数据。
ID Name Value GroupId
4 A 4 2
6 D 6 2
7 E 7 2

//目标数据。
ID Name Value GroupId
1 A 1 1
2 B 2 1
3 C 3 1
4 A 4 2
5 B 5 2

//要得到的数据
ID Name Value GroupId
1 A 1 1
2 B 2 1
3 C 3 1
4 A 4 2
5 B 5 2

6 D 6 2
7 E 7 2
...全文
163 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
iwl 2005-08-19
  • 打赏
  • 举报
回复
delete from tableName
where id not in
(
select min(id) from tableName group by datavar
)
tangqijun199 2005-08-18
  • 打赏
  • 举报
回复
insert into tb
select * from ta a
where not exists (select 1 from tb where id=a.id and GroupId=a.GroupId )
xianggang101 2005-08-18
  • 打赏
  • 举报
回复
insert tb select * from ta union select * from tb where id not in (select id from ta )
xueguang 2005-08-18
  • 打赏
  • 举报
回复
insert tb select * from (select * from ta union select * from tb) A where ID not in(select ID from tb)
filebat 2005-08-17
  • 打赏
  • 举报
回复
下面的方法应该快一些

insert tb
select * from ta
where id in(select min(ta.id)
from ta left join tb
on ta.name=tb.name and ta.groupid=tb.groupid
where tb.id is null
group by ta.name, ta.groupid)
filebat 2005-08-17
  • 打赏
  • 举报
回复
效率不高。
想想,看有没有更好的办法。
yeeyee 2005-08-17
  • 打赏
  • 举报
回复
//源数据。 可以不管 ID
filebat 2005-08-17
  • 打赏
  • 举报
回复
--测试数据ta为源数据, tb为目标数据
create table ta(id int, name varchar(10),
value int, groupid int)
create table tb(id int, name varchar(10),
value int, groupid int)
insert ta select 4,'A',4, 2 union all select 6,'D',6,2
union all select 7,'E',7, 2
insert tb select 1,'A',1, 1 union all select 2,'B',2,1
union all select 3,'C',3, 1 union all select 4,'A',4,2
union all select 5,'B',5, 2
--主要部分
--注意源数据中,也要记得排除重复记录
insert tb
select *
from ta as t1
where not exists(select 1 from tb
where tb.name=t1.name and tb.groupid=t1.groupid)
and exists(select top 1 id from ta
where name=t1.name and groupid=t1.groupid
and id=t1.id)

select * from tb
--清除
drop table ta
drop table tb
yeeyee 2005-08-17
  • 打赏
  • 举报
回复
ID 是主键
filebat 2005-08-17
  • 打赏
  • 举报
回复
源数据中的ID 是主键吗?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧