1、SQL查询去除重复行-- SQL小技巧

大家可能会碰到以下几种情况:

1.存在部分字段相同的纪录,即有唯一键主键ID(最常见情况
如果是这种情况的话用distinct是过滤不了的,这就要用到主键id的唯一性特点及group by分组

select * from table where id in (select max(id) from table group by [去除重复的字段名列表,....])

2、存在两条完全相同的记录(最简单情况)

这是最简单的一种情况,用关键字distinct就可以去掉

select distinct id(某一列) from table(表名) where (条件)

3.没有唯一键ID

这种情况我觉得最复杂,目前未使用过,有那位知道其他方法的可以留言,交流一下:

select identity(int1,1) as id,* into newtable(临时表) from table(原表)
select * from newtable where id in (select max(id) from newtable group by [去除重复的字段名列表,....])
drop table newtable
发布了27 篇原创文章 · 获赞 8 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u014265442/article/details/81087199