码迷,mamicode.com
首页 > 数据库 > 详细

SqlServer去除重复行

时间:2015-07-15 16:44:18      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:


--第一个案例

CREATE TABLE t
(
    id INT IDENTITY(1,1) PRIMARY KEY,
    a VARCHAR(10),
    b VARCHAR(10)
)


--插入数据
INSERT INTO t
SELECT ‘aa‘,‘bb‘ UNION ALL
SELECT ‘a1‘,‘bgb‘ UNION ALL
SELECT ‘aa‘,‘bb‘ UNION ALL
SELECT ‘a2‘,‘bb‘ UNION ALL
SELECT ‘aa3‘,‘beeb‘ UNION ALL
SELECT ‘aa‘,‘bb‘ UNION ALL
SELECT ‘a2‘,‘bb‘

SELECT * FROM t ORDER BY a

--第一种删除重复的方法(找出重复的项的最小标识,删除不包含最小标识的数据)
DELETE t WHERE id NOT IN(
SELECT min(id) id FROM t GROUP BY a,b
)

--第二种删除重复的方法(分区排序,给每个分区排序的结果给个行号,把行号大于1的删除)
DELETE t FROM (
SELECT *,ROW_NUMBER() OVER (PARTITION BY a,b ORDER BY ID) row FROM t)
WHERE ROW>1

 

 

--第二个案例

CREATE TABLE user_student(id decimal(18,0) identity(1,1),st_name nvarchar(30),class nvarchar(10),score decimal(18,2))

insert into user_student(st_name,class,score)
values(‘张三‘,‘甲‘,‘90‘)
insert into user_student(st_name,class,score)
values(‘张四‘,‘甲‘,‘65‘)
insert into user_student(st_name,class,score)
values(‘张五‘,‘甲‘,‘88‘)
insert into user_student(st_name,class,score)
values(‘李三‘,‘乙‘,‘97‘)
insert into user_student(st_name,class,score)
values(‘李四‘,‘乙‘,‘88‘)
insert into user_student(st_name,class,score)
values(‘李五‘,‘乙‘,‘78‘)
insert into user_student(st_name,class,score)
values(‘王三‘,‘丙‘,‘86‘)
insert into user_student(st_name,class,score)
values(‘王四‘,‘丙‘,‘69‘)
insert into user_student(st_name,class,score)
values(‘王五‘,‘丙‘,‘90‘)

select * from user_student

SELECT ST_NAME,CLASS,SCORE
FROM (
SELECT Row_number() OVER(PARTITION BY CLASS ORDER BY SCORE DESC) AS NUM,*
FROM user_student
) AS T
WHERE NUM<=2 --每个班级分数前两名的学生


DELETE user_student FROM  user_student WHERE id NOT IN (SELECT max(id) AS id FROM user_student
GROUP BY st_name,class,score) --删除后来添加的重复数据

SqlServer去除重复行

标签:

原文地址:http://www.cnblogs.com/zylhappyeah/p/4648569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!