sql多欄位去重
『壹』 sql查詢去掉重復記錄
1、打開要去掉重復數據的資料庫,這里新建一張含有重復數據的user表做示例,如下圖所示:
『貳』 關於SQL去重的幾種方法
1. distinct
select distinct 列名 from 表名
2. row_number
select *, row_number() over (partition by 想去重的列名 order by 列名) as row_num
from 表名
where row_num = 1
3.group by
select 列名 from 表名 group by 列名
重復量多時,GROUP BY總的處理效率比DISTINCT高,重復量低時,DISTINCT就比GROUP BY快一點了,而如果隨著整體數據量的增加,效果會越來越明顯。
『叄』 SQL如何去重
1、首先創建一個臨時表,用於演示sqlserver語法中的去重關鍵字distinct的使用。本文以sqlserver資料庫為例演示,
IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;
CREATE TABLE #tmp1(
Col1 varchar(50),
Col2 int
);
『肆』 SQL查詢中如何剔除重復
1,存在兩條完全相同的紀錄
這是最簡單的一種情況,用關鍵字distinct就可以去掉
example: select distinct * from table(表名) where (條件)
2,存在部分欄位相同的紀錄(有主鍵id即唯一鍵)
如果是這種情況的話用distinct是過濾不了的,這就要用到主鍵id的唯一性特點及group by分組
example:
select * from table where id in (select max(id) from table group by [去除重復的欄位名列表,....])
3,沒有唯一鍵ID
example:
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
(4)sql多欄位去重擴展閱讀
1、查找表中多餘的重復記錄,重復記錄是根據單個欄位(peopleId)來判斷
select * from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
2、刪除表中多餘的重復記錄,重復記錄是根據單個欄位(peopleId)來判斷,只留有rowid最小的記錄
delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)
3、查找表中多餘的重復記錄(多個欄位)
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
『伍』 sql語句去重
sql語句通過DISTINCT關鍵字去重, 用於返回唯一不同的值。DISTINCT關鍵字需要搭配SELECT 語句使用,語法為SELECT DISTINCT 列名稱 FROM 表名稱。如果指定了 SELECT DISTINCT,那麼 ORDER BY 子句中的項就必須出現在選擇列表中,否則會出現錯誤。
(5)sql多欄位去重擴展閱讀:
distinct這個關鍵字用來過濾掉多餘的重復記錄只保留一條,但往往只用它來返回不重復記錄的條數,而不是用它來返回不重記錄的所有值。其原因是distinct只有用二重循環查詢來解決,而這樣對於一個數據量非常大的站來說,無疑是會直接影響到效率的。
distinct必須放在開頭,distinct語句中select顯示的欄位只能是distinct指定的欄位,其他欄位是不可能出現的。