27,579
社区成员
发帖
与我相关
我的任务
分享
/*
表A、表B完全相同,表A中存学生成绩,如:
表A
ID 学生姓名 课程名称 分数
ID Sname Cname Score
1 张三 语文 88
2 张三 数学 97
3 张三 数学 98
4 李四 语文 84
5 李四 语文 88
现在要将表A中数据插入表B,要过滤掉一些重复的数据,如张三的数学成绩和李四的语文成功有一条重复数据,只保留分数最高的那一条。过滤后表B的数据为:
表B
ID 学生姓名 课程名称 分数
ID Sname Cname Score
1 张三 语文 88
2 张三 数学 98
3 李四 语文 88 */
use xmmds
go
if(object_id('a') is not null) drop table a
go
create table a
(
id int,
sname varchar(50),
Cname varchar(50),
score int
)
go
insert into a
select 1,'张三','语文',88 union all
select 2,'张三','数学',97 union all
select 3,'张三','数学',98 union all
select 4,'李四','语文',84 union all
select 5,'李四','语文',88
go
if(object_id('b') is not null) drop table b
go
create table b
(
id int,
sname varchar(50),
Cname varchar(50),
score int
)
go
if exists(select * from a inner join b on a.sname=b.sname and a.cname=b.cname)
begin
update b set score = case when b.score >a.score then b.score when b.score<a.score then a.score else b.score end
from b inner join (select sname,cname,max(score) as score from a group by sname,cname)as a on a.sname=b.sname and a.cname=b.cname
end
else
begin
insert into b(sname,cname,score)
select sname,cname,max(score) as score
from a
group by sname,cname
end
/*(3 行受影响)*/
select sname,cname,score from b
/*
sname cname score
-------------------------------------------------- -------------------------------------------------- -----------
张三 数学 98
李四 语文 88
张三 语文 88
(3 行受影响)
*/
with tb(id ,Sname,Cname , Score , CreateTime ,Other )
as
(select 1, '张三','语文',88,'2010-01-01','' union all
select 2, '张三','数学',97,'2010-01-01','' union all
select 3,'张三', '数学',98,'2010-01-01','' union all
select 4,'李四', '语文',84,'2010-01-01','' union all
select 5, '李四', '语文', 88,'2010-01-01',''
)
select * from tb tb1 where id in(select id from tb tb2 where tb1.Sname=tb2.Sname and tb1.Cname=tb2.Cname and tb2.Score=
(select max(Score) from tb tb3 where tb3.Sname=tb2.Sname and tb2.Cname=tb3.Cname))
insert into b(id,sname,cname,score)
select id=row_number() over(order by getdate()),
sname,cname,max(score) as score
from tb
group by sname,cname