查詢去重
distinct去重
select DISTINCT * from 表
解析:distinct去重很簡單只用在查詢字段前面加入distinct關鍵字就行,但此做法有一個問題,就是必須要所有的查詢字段一模一樣才能去重,如果其中有一個字段不重復就無法去重
group by 去重
select 查詢字段 from 表 where id in(select max(id) from 表 group by 去重分組字段)
解析:首先以要去重的字段分組 取得組內最大的id 然后根據id 查詢的對應的信息就好,此方法需要有唯一字段,如:主鍵Id
沒有唯一鍵group by 去重
select identity(int,1,1) as id,* into newtable(臨時表) from 表 select * from newtable where id in (select max(id) from newtable group by 去重分組字段) drop table newtable
解析:先將表into 寫入到臨時表newtable並加入自增Id,后續操作和group by 去重一致,然后刪除(drop table)臨時表