How to retrieve duplicate rows in a table?
How to delete the duplicate entries in a table?

Answer Posted / sameer

--select * from #TempR
select * into #temp2 from #TempR

-- select * from #temp2

alter table #temp2 add record_id numeric(5,0) identity not
null

/* select those row which are repeated */

select * into #qwe
from #temp2
where exists(

select null from #temp2 b
where b.ID = #temp2.ID
and b.TYPE = #temp2.TYPE
group by b.ID, b.TYPE
having
count (*) >=2
)

--select * from #qwe




/* delete those row which are repeted */

delete from #TempR where ID in ( select ID from #qwe)

/* insert those row which are deleted */

delete from #qwe where record_id not in (

select record_id
from #qwe
group by ID, TYPE
having record_id = max (record_id)
)

-- select * from #qwe
alter table #qwe drop record_id

insert into #TempR
select * from #qwe

/* see output */


select * from #TempR

/* check for row getting repeted */


select *
from #TempR
where exists(

select null from #TempR b
where b.ID = #TempR.ID
and b.TYPE = #TempR.TYPE
group by b.TT_ID, b.EQP_TYPE
having
count (*) >=2
)

Is This Answer Correct ?    1 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Which is the best place or learning center for MS SQL?????In Bangladesh?????

1596


How do I find the sql server instance name?

531


What is the difference between dbcc indexdefrag and dbcc reindex?

527


What is the syntax to execute the sys.dm_db_missing_index_details?

588


How do I uninstall sql server 2014?

526






What is save transaction and save point?

630


Is it possible for a stored procedure to call itself or recursive stored procedure?

512


What does dml stand for?

512


Mention the differences between local and global temporary tables.

575


Explain optimistic and pessimistic concurrency?

544


What is triggers in ms sql server?

643


What is index in an assignment?

535


What is difference between views and stored procedures?

516


If you're given a raw data table, how would perform etl (extract, transform, load) with sql to obtain the data in a desired format?

553


Issues related in upgrading SQL Server 2000 to 2005 / 2008

1506