去重復sql語句
A. 在sql語言中去掉重復值的命令是
distinct。
SQLserver中很明顯的去重復的語句是distinct。selectdistinct是去除重復的記錄行,count(distinctColumn),消除重復值。還有一些不明顯的具有去重功能的詞,例如union,會去除重復的記錄行或值。
B. sql查詢去掉重復記錄
1、打開要去掉重復數據的資料庫,這里新建一張含有重復數據的user表做示例,如下圖所示:
C. SQL如何去重
1、首先創建一個臨時表,用於演示sqlserver語法中的去重關鍵字distinct的使用。本文以sqlserver資料庫為例演示,
IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;
CREATE TABLE #tmp1(
Col1 varchar(50),
Col2 int
);
D. sql 語句去掉復重復的記錄
col1
中有重復記錄(col1,col2為主鍵),如何刪除
1、有少數重復記錄(在col1,col2上有索引比較好)
delete
t
where
(col1,col2)
in
(select
col1,col2
from
t
group
by
col1,col2
having
count(*)
>
1)
and
rowid
not
in
(select
min(rowid)
from
t
group
by
col1,col2
having
count(*)
>
1)
2、大部份記錄有重復記錄
delete
t
where
rowid
not
in
(select
min(rowid)
from
t
group
by
col1,col2)
3、其他寫法
delete
t
where
rowid
in
(select
a.rowid
from
t
a,t
b
where
a.col1=b.col1
and
a.col2
=
b.col2
and
a.rowid
>
b.rowid)
######################################
10.
刪除重復記錄
最高效的刪除重復記錄方法
(
因為使用了rowid)
delete
from
emp
e
where
e.rowid
>
(select
min(x.rowid)
from
emp
x
where
x.emp_no
=
e.emp_no);
11.
用truncate替代delete
當刪除表中的記錄時,在通常情況下,
回滾段(rollback
segments
)
用來存放可以被恢復的信息.
如果你沒有commit事務,oracle會將數據恢復到刪除之前的狀態(准確地說是
恢復到執行刪除命令之前的狀況)
而當運用truncate時,
回滾段不再存放任何可被恢復的信息.當命令運行後,數據不能被恢復.因此很少的資源被調用,執行時間也會很短.
(譯者按:
truncate只在刪除全表適用,truncate是ddl不是dml)
12.
盡量多使用commit
只要有可能,在程序中盡量多使用commit,
這樣程序的性能得到提高,需求也會因為commit所釋放的資源而減少:
commit所釋放的資源:
a.
回滾段上用於恢復數據的信息.
b.
被程序語句獲得的鎖
c.
redo
log
buffer
中的空間
d.
oracle為管理上述3種資源中的內部花費
E. SQL查詢中如何剔除重復
1、存在部分欄位相同的紀錄
如果是這種情況的話用distinct是過濾不了的,這就要用到主鍵id的唯一性特點及group
代碼:select
*
from
table
where
id
in
(select
max(id)
from
table
group
by
[去除重復的欄位名列表,....])
2、存在兩條完全相同的記錄
這是最簡單的一種情況,用關鍵字distinct就可以去掉
代碼:select
distinct
*
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
(5)去重復sql語句擴展閱讀:
SQL查詢語句
1、查詢全部的重復信息
select
*
from
people
where
id
not
in
(
select
min(id)
from
people
group
by
name,sex
HAVING
COUNT(*)
<
2)
2、查詢多餘的重復信息
select
*
from
people
where
id
not
in
(
select
MIN(id)
from
people
group
by
name,sex)
F. sql中如何刪除一個表中重復的記錄
sql中刪除一個表中的重復記錄可以採用如下步驟:
1、把a_dist表的記錄用distinct去重,結果放到臨時表中。
select distinct * into #temp from a_dist;
2、把a_dist表的記錄全部刪除。
delete from a_dist;
3、把臨時表中的數據信息導進到a_dist表中,並刪除臨時表。
insert into a_distselect * from #temp;
drop table #temp;
(6)去重復sql語句擴展閱讀:
SQL (結構化查詢語言)是用於執行查詢的語法。在資料庫上執行的大部分工作都由 SQL 語句完成。SQL 語言包含用於更新、插入和刪除記錄的語法。
增刪改查指令構成了 SQL 的 DML 部分:
SELECT- 從資料庫表中獲取數據
UPDATE- 更新資料庫表中的數據
DELETE- 從資料庫表中刪除數據
INSERT INTO- 向資料庫表中插入數據
G. SQL查詢,如何去除重復的記錄
首先,先說明一個問題。這樣的結果出現,說明系統設計是有問題的。
其次
刪除重復數據,你要提供你是什麼資料庫。
不同資料庫會有不同的解決方案。
關鍵字Distinct 去除重復,如下列SQL,去除Test相同的記錄;
1. select distinct Test from Table
2. 如果是要刪除表中存在的重復記錄,那就邏輯處理,如下:
3. select Test from Table group by Test having count(test)>1
4. 先查詢存在重復的數據,後面根據條件刪除
還有一個更簡單的方法可以嘗試一下:
select aid, count(distinct uid) from 表名 group by aid
這是sqlserver 的寫法。
如圖一在數據表中有兩個膀胱沖洗重復的記錄。