标签:
--第一个案例
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) --删除后来添加的重复数据
标签:
原文地址:http://www.cnblogs.com/zylhappyeah/p/4648569.html