--處理表重復記錄(查詢和刪除)
/******************************************************************************************************************************************************
1、Num、
Name
相同的重復值記錄,沒有大小關系只保留一條
2、
Name
相同,ID有大小關系時,保留大或小其中一個記錄
******************************************************************************************************************************************************/
--1、用于查詢重復處理記錄(如果列沒有大小關系時2000用生成自增列和臨時表處理,SQL2005用row_number函數處理)
-->-->生成測試數據
if
not
object_id(
'Tempdb..#T'
)
is
null
drop
table
#T
Go
Create
table
#T([ID]
int
,[
Name
]nvarchar(1),[Memo]nvarchar(2))
Insert
#T
select
1,N
'A'
,N
'A1'
union
all
select
2,N
'A'
,N
'A2'
union
all
select
3,N
'A'
,N
'A3'
union
all
select
4,N
'B'
,N
'B1'
union
all
select
5,N
'B'
,N
'B2'
Go
--I、Name相同ID最小的記錄(推薦用1,2,3),方法3在SQl05時,效率高于1、2
方法1:
Select
*
from
#Ta
where
not
exists(
select
1
from
#T
where
Name
=a.
Name
and
ID<a.ID)
方法2:
select
a.*
from
#Ta
join
(
select
min
(ID)ID,
Name
from
#T
group
by
Name
)b
on
a.
Name
=b.
Name
and
a.ID=b.ID
方法3:
select
*
from
#Ta
where
ID=(
select
min
(ID)
from
#T
where
Name
=a.
Name
)
方法4:
select
a.*
from
#Ta
join
#Tb
on
a.
Name
=b.
Name
and
a.ID>=b.ID
group
by
a.ID,a.
Name
,a.Memo
having
count
(1)=1
方法5:
select
*
from
#Ta
group
by
ID,
Name
,Memo
having
ID=(
select
min
(ID)
from
#T
where
Name
=a.
Name
)
方法6:
select
*
from
#Ta
where
(
select
count
(1)
from
#T
where
Name
=a.
Name
and
ID<a.ID)=0
方法7:
select
*
from
#Ta
where
ID=(
select
top
1ID
from
#T
where
Name
=a.
name
order
by
ID)
方法8:
select
*
from
新聞熱點
疑難解答