Showing posts with label duplicate. Show all posts
Showing posts with label duplicate. Show all posts

Thursday, March 22, 2012

Deleting duplicate rows within a single table

I was wondering if anyone had a suggestion as to how to delete duplicate rows from a table. I have been doing this:

SELECT * INTO TempUsersNoRepeats
FROM TempUsers2
UNION
SELECT * FROM TempUsers3

This way I end up with a total of four tables (the fourth table being the original Users table) and I was hoping that there was a way that I could do this all within the the original Users table and not have to create the three TempUsers tables.

Thanks,
RonDo you have a primary key on the table?|||Douglas,

Thanks for the reply. These tables are staging tables and not part of my asp.net application as they are made from .csv files that I get from FOCUS jobs from a mainframe. I cannot add a PK as there are so many duplicate rows. The table cols are:

FacultyID,FacultyPW,FacultyFName,FacultyLName,FacultyEmailID

I could add a Identity col to get some unique values assoc. with each row though.

Thanks,
Ronald|||If you add an IDENTITY field (lets say, named ID):


DELETE FROM Faculty WHERE ID IN (
SELECT MAX(ID) FROM Faculty
GROUP BY
FacultyID,FacultyPW,FacultyFName,FacultyLName,FacultyEmailID
HAVING COUNT(*)>1
)

This will delete one row of the duplicates that are complete dups except the new ID field. Please try this on a test database first! This is untested SQL, but I believe it will work.|||Douglas,

Thanks that was pretty cool. If you could possibly answer one more question, some of the rows are duplicated multiple times, there could be one Faculty row 7 times (they are teaching 7 courses that semester) or some are just teaching 5 times thus only showing 5 dupes.

What would the proper syntax be for the HAVING COUNT(*)>1 so that I either catch a range (say 1-20) or for it to loop maybe.

I kept running the above script and was able to clear out all the duplicates after several runs.

Thanks very much,
Ronald|||This will delete one duplicate for each exact duplicate. If you have 20 identical duplicates, you would need to use the query 20 times (run it until 0 rows are effected).

Alternately, you could play and make it a query that deletes those dupes that are NOT MAX(ID).

Deleting Duplicate Rows in SQL Table

I have an SQL tables [Keys] that has various rows such as:
[ID] [Name] [Path] [Customer]
1 Key1 Key1 InHouse
2 Key2 Key2 External
3 Key1 Key1 InHouse
4 Key1 Key1 InHouse
5 Key1 Key1 InHouse

Obviously IDs 1,3,4,5 are all exactly the same and I would like to be left with only:
[ID] [Name] [Path] [Customer]
1 Key1 Key1 InHouse
2 Key2 Key2 External

I cannot create a new table/database or change the unique identifier (which is currently ID) either. I simply need an SQL script I can run to clean out the duplicates (I know how they got there and the issue has been fixed but the Database is still currently invalid due to all these duplicate entires).

Any help would be greatly appreciated.
Thanks,Since you want nothing left in your table (see your example above), a simple TRUNCATE TABLE should do nicely!

-PatP|||Pat: Funny :) Sorry I posted that too quick, updated it now.
Thanks,|||Oh, so now you get picky about things! ;)

Try this:DELETE FROM myTable
WHERE EXISTS (SELECT *
FROM myTable AS foo
WHERE foo.[name] = myTable.[name]
AND foo.[path]= myTable.[path]
AND myTable.[id] < foo.[id]-PatP

Deleting duplicate rows in a table

In Sql Server table , there are some duplicate rows
i want to delete the duplicate rows without using Cursors and Temp TableCREATE PROCEDURE RemoveDuplicate AS
Begin
SET NOCOUNT ON
--
DECLARE @.iErrorVar int,
@.CertificateID INT,
@.ClientID INT,
@.iCount int,
@.chCount char(3),
@.nvchCommand nvarchar(4000)
-- set initial environment
SET ROWCOUNT 0
-- Build cursor to find duplicated information

--Change this from a cursor to a table variable. This is an early version
-- of the code before I tarted it up a bit.

DECLARE DelDupe CURSOR FOR
SELECT COUNT(*) AS Amount,
fields that make the row distinct
FROM Table
GROUP BY Fields
HAVING COUNT(*) > 1

OPEN DelDupe
FETCH NEXT FROM DelDupe
INTO @.FieldVars,

WHILE (@.@.fetch_status = 0)
BEGIN
-- Calculate number of rows to delete for each grouping by subtracting
-- 1 from the total count for a given group.

SELECT @.iCount = @.iCount - 1
SELECT @.chCount = CONVERT(char(3),@.iCount)
-- now build the rowcount and delete statements.
SELECT @.nvchCommand = N'SET ROWCOUNT ' + @.chCount +
'DELETE FROM Table ' +
' WHERE All Fields match those in the field variables. = ' + convert(varchar,@.Field1) +
' AND Etc = ' + convert(varchar,@.Field2)

--
-- print @.nvchCommand --Use this to check the syntax
EXEC sp_executesql @.nvchCommand --Comment out until happy.
--
FETCH NEXT FROM DelDupe
INTO @.iCount,
@.CertificateID,
@.ClientID
END
--
CLOSE DelDupe
DEALLOCATE DelDupe
End

This is the easiest way I've found to do removal of dups. Hope it helps.

Cheers
C|||

Quote:

Originally Posted by thithu

In Sql Server table , there are some duplicate rows
i want to delete the duplicate rows without using Cursors and Temp Table


try the following and adapt it to your needs:

create table #t1 (id int identity(1,1), x char(5))
insert into #t1 (x) values ('a')
insert into #t1 (x) values ('a')
insert into #t1 (x) values ('a')
insert into #t1 (x) values ('b')
insert into #t1 (x) values ('b')
insert into #t1 (x) values ('b')
insert into #t1 (x) values ('c')
insert into #t1 (x) values ('d')
insert into #t1 (x) values ('d')

select * from #t1

delete from #t1
where x in (select x from #t1 group by x having count(*) > 1)
and id not in (select min(id) from #t1 group by x having count(*) > 1)

select * from #t1

Deleting duplicate rows from a table, having no primary key

I am looking at various methods to delete records from a table which has duplicate records and does not have a foriegn key, in a single query.
One of the methods is using the rowid.
Looking for more.
VisheetalThat would be the easiest.sql

Deleting duplicate rows from a table without using temporary table

Hi all ,
Can anyone tell me the query to delete the duplicates from a table
CASE_COUNTRY
Country CountryCode
-- --
France FR
France FR
Italy IT
Germany GM
Here France is a duplicate row , i have 10000 records like this
Regards
AlertAdminAlertAdmin wrote:
> Hi all ,
> Can anyone tell me the query to delete the duplicates from a table
> CASE_COUNTRY
> Country CountryCode
> -- --
> France FR
> France FR
> Italy IT
> Germany GM
>
> Here France is a duplicate row , i have 10000 records like this
>
> Regards
> AlertAdmin
You could try the following. I'm not sure what advantage if any that
this would have over using a temp table.
BEGIN TRAN
GO
CREATE TRIGGER trg_case_country ON case_country
FOR DELETE
AS
INSERT INTO case_country (country, countrycode)
SELECT DISTINCT country, countrycode
FROM deleted ;
GO
DELETE FROM case_country ;
DROP TRIGGER trg_case_country;
COMMIT TRAN
GO
The most important step comes next. Add the missing keys:
ALTER TABLE case_country
ADD CONSTRAINT pk_case_country PRIMARY KEY (countrycode);
ALTER TABLE case_country
ADD CONSTRAINT ak1_case_country UNIQUE (country);
Your choice of country code for Germany is unusual. I suggest you use
the ISO standard country codes unless you are working to some unique
standard that requires otherwise:
http://www.iso.ch/iso/en/prods-serv...ex.html

David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||AlertAdmin wrote:
> Hi all ,
> Can anyone tell me the query to delete the duplicates from a table
> CASE_COUNTRY
> Country CountryCode
> -- --
> France FR
> France FR
> Italy IT
> Germany GM
>
> Here France is a duplicate row , i have 10000 records like this
>
> Regards
> AlertAdmin
In SQL Server 2005 the following also works for me, although I'm not
certain that this behaviour is well-documented or totally reliable.
CREATE TABLE case_country (country VARCHAR(35) NOT NULL, countrycode
CHAR(2) NOT NULL /* NO KEY! */);
INSERT INTO case_country VALUES ('France', 'FR');
INSERT INTO case_country VALUES ('France', 'FR');
INSERT INTO case_country VALUES ('Italy', 'IT');
INSERT INTO case_country VALUES ('Germany', 'GM');
WITH T AS
(SELECT country, countrycode, ROW_NUMBER()
OVER (PARTITION BY country, countrycode
ORDER BY country, countrycode) AS row_num
FROM case_country)
DELETE FROM T
WHERE row_num>1;
SELECT * FROM case_country;
Result:
country countrycode
-- --
France FR
Italy IT
Germany GM
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Thanks alot , it works fine for me
Regards
AlertAdmin|||And don't forget to add the primary key and unique constraint!
Hope this helps.
Dan Guzman
SQL Server MVP
"AlertAdmin" <sajin@.iprlab.com> wrote in message
news:1141472981.407005.316810@.z34g2000cwc.googlegroups.com...
> Thanks alot , it works fine for me
> Regards
> AlertAdmin
>|||Hi,
I got another solution by adding a identity column
alter table case_country add test_iden int identity(1,1)
delete from case_country where test_iden not in (select min(test_iden)
from tab group by country)
alter table tab drop column test_iden
Regards
AlertAdmin

Deleting duplicate records from a table.....

I loaded one table via SSIS and found that it contained many duplicate records (from the input source). I can create a SQL task to delete them, but I wonder if SSIS offers and task "out of the box" to delete dups?

TAI,

barkingdog

I don't know about anything in SSIS to do so but here's a great way to do it using CTE's and Row_Number()

http://www.sqlservercentral.com/columnists/chawkins/dedupingdatainsqlserver2005.asp

|||

Use a Sort transform from SSIS is a possible alternation - Sort on certain keys and check "remove duplicate records" at Sort transform.

hth

wenyang

Deleting duplicate records

Hi All,
I am having one table named MyTable and this table contains only one column MyCol. Now i m having 10 records in it and all the records are duplicate ie value is 7 for all 10 records.

It is something like this,

MyCol
7
7
7
7
7
7
7
7
7
7

Now i m trying to delete 10th record or any record then it gives me error
"Key column information is insufficient or incorrect. Too many rows were affected by update."

What should i do if i want only 4 records insted 10 records in my table?
How do i delete the 6 records from table?

Plz help me.

Regards,
ShaileshSince there seems to be no (primary) key to identity the row there's nothing left than a workaround, which basically will delete all rows with, in this case, mycol on 7, and inserts four (your case) new records with the value 7.|||this could work for you:

set rowcount 4

delete from table_name

set rowcount 0 --set back to affect all rows

mojza|||Hi,
you can also temporary add one identity column and delete all the record that you dont need. After finish drop the new added identity column.

Deleting Duplicate Records

I have a table tmPunchtimeSummary which contains a sum of employee's hours
per day. The table contains some duplicates.
code:

CREATE TABLE [tmPunchtimeSummary]
(
[iTmPunchTimeSummaryId] [int] IDENTITY (1, 1) NOT NULL ,
[sCalldate] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[sEmployeeId] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[dTotalHrs] [decimal](18, 4) NULL
) ON [PRIMARY]
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '1234', 4.5)
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '1234', 4.5)
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '2468', 8.0)
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '1357', 9.0)
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '2345', 8.5)
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
VALUES('20060610', '2345', 8.5


How can I write a delete statement to only delete the duplicates which in
this case would be the 1st and 5th records?
Thanks,
Ninel
Message posted via http://www.webservertalk.comDELETE FROM tmPunchtimeSummary
WHERE EXISTS
(select * from tmPunchtimeSummary as X
where tmPunchtimeSummary.sCalldate = X.sCalldate
and tmPunchtimeSummary.sEmployeeId = X.sEmployeeId
and tmPunchtimeSummary.dTotalHrs = X.dTotalHrs
and tmPunchtimeSummary.iTmPunchTimeSummaryId <
X.iTmPunchTimeSummaryId)
Roy Harvey
Beacon Falls, CT
On Wed, 14 Jun 2006 16:41:01 GMT, "ngorbunov via webservertalk.com"
<
u9125@.uwe>
wrote:

>
I have a table tmPunchtimeSummary which contains a sum of employee's hours
>
per day. The table contains some duplicates.
>
>
code:

>
CREATE TABLE [tmPunchtimeSummary]
>
(
>
[iTmPunchTimeSummaryId] [int] IDENTITY (1, 1) NOT NULL ,
>
[sCalldate] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
>
[sEmployeeId] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
>
[dTotalHrs] [decimal](18, 4) NULL
>
) ON [PRIMARY]
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '1234', 4.5)
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '1234', 4.5)
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '2468', 8.0)
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '1357', 9.0)
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '2345', 8.5)
>
>
INSERT tmPunchtimeSummary (sCalldate, sEmployeeId, dTotalHrs)
>
VALUES('20060610', '2345', 8.5
>


>
>
How can I write a delete statement to only delete the duplicates which in
>
this case would be the 1st and 5th records?
>
>
Thanks,
>
Ninel|||Thank you very much.
Roy Harvey wrote:
>DELETE FROM tmPunchtimeSummary
> WHERE EXISTS
> (select * from tmPunchtimeSummary as X
> where tmPunchtimeSummary.sCalldate = X.sCalldate
> and tmPunchtimeSummary.sEmployeeId = X.sEmployeeId
> and tmPunchtimeSummary.dTotalHrs = X.dTotalHrs
> and tmPunchtimeSummary.iTmPunchTimeSummaryId <
> X.iTmPunchTimeSummaryId)
>Roy Harvey
>Beacon Falls, CT
>
>[quoted text clipped - 32 lines]
Message posted via webservertalk.com
http://www.webservertalk.com/Uwe/Forum...amming/200606/1|||> DELETE FROM tmPunchtimeSummary
> WHERE EXISTS
In my figuring on paper, Roy's solution works.
I also offer another suggetion: Microsoft Access has lots and lots of
wizards to do hard stuff like that. So if you have a copy of Access, let it
be your quick-and-dirty friend. You can use the Access wizard to buzz up
some stuff really fast, and then just paste the SQL code into QA, clean it
up a bit, and then run it.
But I will warn you: Access is not up to the task of production code.
Peace & happy computing,
Mike Labosh, MCSD MCT
Owner, vbSensei.Com
"Escriba coda ergo sum." -- vbSensei

deleting duplicate records

dear friends,
suppose i've one table, it has only to rows.the two rows are are same as it is.how can i delete one row from that table?

thank you verymuchSELECT DISTINCT *
INTO #HOLDING
FROM >your table<
GO
TRUNCATE TABLE >your table<
GO
INSERT >your table<
SELECT *
FROM #HOLDING
GO
DROP TABLE #HOLDING
GO|||you can add another column of type bigint make it auto increment by setting Identity properties to Yes. then you can mannually delete the row :)

Quote:

Originally Posted by vinod

dear friends,
suppose i've one table, it has only to rows.the two rows are are same as it is.how can i delete one row from that table?

thank you verymuch

sql

Deleting duplicate records

I have a table with 25000 records from which to delete 600
duplicate records. for example, col2 has some values with
2 or more entries. When I execute the below script, I
keep getting errors as indicated below. What is the best
way to delete these 600 duplicates.
script file:
SELECT DISTINCT *
INTO test
FROM livetable
GROUP BY col2
HAVING COUNT(col2) > 1
DELETE livetable
WHERE col2
IN (SELECT col2
FROM test)
INSERT Documents_Convert
SELECT *
FROM test
DROP TABLE test
ERROR MESSAGE:
-- when I run the first part of the script, i get the
bellow error:
--Server: Msg 8120, Level 16, State 1, Line 1
Column 'livetable.col1' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.
--Server: Msg 8120, Level 16, State 1, Line 1
Column 'livetable.col2' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.
--Server: Msg 8120, Level 16, State 1, Line 1
column 'livetable.col3' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.Hi:
I think the error is becasue the misunderstand of select..group by
statement.
If you want to use group by statement, the content you select should in
the group by or have a function tell the machine how to modify the data.
Best Wishes
Wei Ci Zhou|||I believe that you are using group by uneccessarily.
the distinct should give you a unique subset
try omitting the group by clause .
Scott J Davis
Ruprect@.satx.rr.com
Posted using Wimdows.net NntpNews Component - Posted from SQL Servers Largest Community
Website: http://www.sqlJunkies.com/newsgroups/|||Scott,
What should I do to delete these records' Can you help
with a better script?
Thanks.
Laila
quote:

>--Original Message--
>I believe that you are using group by uneccessarily.
>the distinct should give you a unique subset
>try omitting the group by clause .
>Scott J Davis
>Ruprect@.satx.rr.com
>--
>Posted using Wimdows.net NntpNews Component - Posted from

SQL Servers Largest Community Website:
http://www.sqlJunkies.com/newsgroups/
quote:

>.
>
|||Wei,
What should I do to delete these records' Can you help
with a better script?
Thanks.
Laila
quote:

>--Original Message--
>Hi:
> I think the error is becasue the misunderstand of

select..group by
quote:

>statement.
> If you want to use group by statement, the content you

select should in
quote:

>the group by or have a function tell the machine how to

modify the data.
quote:

>Best Wishes
>Wei Ci Zhou
>
>.
>
|||Hi Laila,
This might be helpful..
http://www.developerfusion.com/show/1976/
Regards
Thirumal Reddy
quote:

>--Original Message--
>Wei,
>What should I do to delete these records' Can you

help
quote:

>with a better script?
>Thanks.
>Laila
>
>
>select..group by
you[QUOTE]
>select should in
>modify the data.
>.
>
|||It seems that the sample does not work on my machine when I use (field,
field) in (....)
And After I read the BOL, it seems that we can use in statement in one
field, do you have any suggestion?

Deleting duplicate records

I have a table with 25000 records from which to delete 600
duplicate records. for example, col2 has some values with
2 or more entries. When I execute the below script, I
keep getting errors as indicated below. What is the best
way to delete these 600 duplicates.
script file:
SELECT DISTINCT *
INTO test
FROM livetable
GROUP BY col2
HAVING COUNT(col2) > 1
DELETE livetable
WHERE col2
IN (SELECT col2
FROM test)
INSERT Documents_Convert
SELECT *
FROM test
DROP TABLE test
ERROR MESSAGE:
-- when I run the first part of the script, i get the
bellow error:
--Server: Msg 8120, Level 16, State 1, Line 1
Column 'livetable.col1' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.
--Server: Msg 8120, Level 16, State 1, Line 1
Column 'livetable.col2' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.
--Server: Msg 8120, Level 16, State 1, Line 1
column 'livetable.col3' is invalid in the select list
because it is not contained in either an aggregate
function or the GROUP BY clause.Hi:
I think the error is becasue the misunderstand of select..group by
statement.
If you want to use group by statement, the content you select should in
the group by or have a function tell the machine how to modify the data.
Best Wishes
Wei Ci Zhou|||I believe that you are using group by uneccessarily.
the distinct should give you a unique subset
try omitting the group by clause .
Scott J Davis
Ruprect@.satx.rr.com
--
Posted using Wimdows.net NntpNews Component - Posted from SQL Servers Largest Community Website: http://www.sqlJunkies.com/newsgroups/|||Scott,
What should I do to delete these records' Can you help
with a better script?
Thanks.
Laila
>--Original Message--
>I believe that you are using group by uneccessarily.
>the distinct should give you a unique subset
>try omitting the group by clause .
>Scott J Davis
>Ruprect@.satx.rr.com
>--
>Posted using Wimdows.net NntpNews Component - Posted from
SQL Servers Largest Community Website:
http://www.sqlJunkies.com/newsgroups/
>.
>|||Wei,
What should I do to delete these records' Can you help
with a better script?
Thanks.
Laila
>--Original Message--
>Hi:
> I think the error is becasue the misunderstand of
select..group by
>statement.
> If you want to use group by statement, the content you
select should in
>the group by or have a function tell the machine how to
modify the data.
>Best Wishes
>Wei Ci Zhou
>
>.
>|||Hi Laila,
This might be helpful..
http://www.developerfusion.com/show/1976/
Regards
Thirumal Reddy
>--Original Message--
>Wei,
>What should I do to delete these records' Can you
help
>with a better script?
>Thanks.
>Laila
>
>>--Original Message--
>>Hi:
>> I think the error is becasue the misunderstand of
>select..group by
>>statement.
>> If you want to use group by statement, the content
you
>select should in
>>the group by or have a function tell the machine how to
>modify the data.
>>Best Wishes
>>Wei Ci Zhou
>>
>>.
>.
>|||It seems that the sample does not work on my machine when I use (field,
field) in (....)
And After I read the BOL, it seems that we can use in statement in one
field, do you have any suggestion?

deleting duplicate record

hi to all,
How to delete duplicate record in the recordset?
Thanks...There must be a dozen ways to do this. Which is easiest and most efficient depends upon your situation.
Explain your issue in more detail, including how often this will need to be done, and give us the layout of your table.|||Hi,

Thanks for the help but I already delete the duplicate record, but I want to knew what is stored procedure? Can give a sample of a store procedure.

Thanks..|||A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.

Stored procedures assist in achieving a consistent implementation of logic across applications. The SQL statements and logic needed to perform a commonly performed task can be designed, coded, and tested once in a stored procedure. Each application needing to perform that task can then simply execute the stored procedure. Coding business logic into a single stored procedure also offers a single point of control for ensuring that business rules are correctly enforced.

This is just a tip of an iceberg..For more info refer Books online.

deleting duplicate record

in my table, I have several rows that are complete duplicates. Needless to
say, I can't open the table and just delete 1 row.
How do I delete the copies and not all?
Take a look at this link.
I've used it in the past to remove thousands of duplicates (dont ask how
they got there )
Once you've gotten rid of the dups, whack some contraints on where
necessary.
http://support.microsoft.com/default...b;en-us;139444
Immy
"Johnfli" <john@.ivhs.us> wrote in message
news:eXaiytCLGHA.1272@.TK2MSFTNGP10.phx.gbl...
> in my table, I have several rows that are complete duplicates. Needless
> to say, I can't open the table and just delete 1 row.
> How do I delete the copies and not all?
>
>

deleting duplicate record

in my table, I have several rows that are complete duplicates. Needless to
say, I can't open the table and just delete 1 row.
How do I delete the copies and not all?Take a look at this link.
I've used it in the past to remove thousands of duplicates (dont ask how
they got there :) )
Once you've gotten rid of the dups, whack some contraints on where
necessary.
http://support.microsoft.com/default.aspx?scid=kb;en-us;139444
Immy
"Johnfli" <john@.ivhs.us> wrote in message
news:eXaiytCLGHA.1272@.TK2MSFTNGP10.phx.gbl...
> in my table, I have several rows that are complete duplicates. Needless
> to say, I can't open the table and just delete 1 row.
> How do I delete the copies and not all?
>
>sql

deleting duplicate record

in my table, I have several rows that are complete duplicates. Needless to
say, I can't open the table and just delete 1 row.
How do I delete the copies and not all?Take a look at this link.
I've used it in the past to remove thousands of duplicates (dont ask how
they got there )
Once you've gotten rid of the dups, whack some contraints on where
necessary.
http://support.microsoft.com/defaul...kb;en-us;139444
Immy
"Johnfli" <john@.ivhs.us> wrote in message
news:eXaiytCLGHA.1272@.TK2MSFTNGP10.phx.gbl...
> in my table, I have several rows that are complete duplicates. Needless
> to say, I can't open the table and just delete 1 row.
> How do I delete the copies and not all?
>
>

Deleting duplicate entries in nightmare-table

Hello
I was given the task to "filter away" duplicate rows in a 10 million row
table with about 30 columns :S And the table has no primary key, no
constrains, nothing, and I need to find a way to clear that mess up, in a
way... sigh
You guys must think, alright, this is easy, just group by, well well, that
would be too easy, since each row isnt really "unique", lets continue the
mess....
Lets say the table contains 5 columns, A B C D E
In the new table there shall be a CHECK(A,B,C), that combination is unique.
But in the old table there are duplicates of that, and the values of D and E
may be any value on each row. (Headache yet?) Ppl who create these kinds of
heaptables should be lined up and shot :(
Lemme post some test DLL:
CREATE TABLE #Test (
A int,
B int,
C int,
D int,
E int
)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,8)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,6)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,2,1,1,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,1,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
SELECT * FROM #Test
/*
DESIRED RESULT
A B C D E
1,1,1,9,8
1,2,1,1,4
3,2,1,1,4
*/
DROP TABLE #Test
And everything is so screwed up it doesnt "matter" which values D and E has
(or the other 20 columns) as long as they had the value it had before. And
all columns are like varchar(x) in the table, so keep that in mind :S> And everything is so screwed up it doesnt "matter" which values D and E
> has
> (or the other 20 columns) as long as they had the value it had before.
This doesn't make sense to me, which value did it have before?
Anyway, I'll try, can you do this:
SELECT A,B,C,MAX(D),MAX(E)
FROM table
GROUP BY A,B,C;
?
There is no ANY() function, so you either need to choose an aggregate, or
maybe you could use a correlated subquery with ORDER BY CHECKSUM(NEWID())
but I'm not clear that would work, nor without better requirements am I
inclined to try.
A|||Lasse Edsvik wrote:
> Hello
> I was given the task to "filter away" duplicate rows in a 10 million row
> table with about 30 columns :S And the table has no primary key, no
> constrains, nothing, and I need to find a way to clear that mess up, in a
> way... sigh
> You guys must think, alright, this is easy, just group by, well well, that
> would be too easy, since each row isnt really "unique", lets continue the
> mess....
> Lets say the table contains 5 columns, A B C D E
> In the new table there shall be a CHECK(A,B,C), that combination is unique
.
> But in the old table there are duplicates of that, and the values of D and
E
> may be any value on each row. (Headache yet?) Ppl who create these kinds o
f
> heaptables should be lined up and shot :(
> Lemme post some test DLL:
>
> CREATE TABLE #Test (
> A int,
> B int,
> C int,
> D int,
> E int
> )
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,8)
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,6)
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,2,1,1,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,1,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
>
> SELECT * FROM #Test
> /*
> DESIRED RESULT
>
> A B C D E
> 1,1,1,9,8
> 1,2,1,1,4
> 3,2,1,1,4
> */
> DROP TABLE #Test
>
> And everything is so screwed up it doesnt "matter" which values D and E ha
s
> (or the other 20 columns) as long as they had the value it had before. And
> all columns are like varchar(x) in the table, so keep that in mind :S
Always tell us what version of SQL Server you are using.
In SQL Server 2005:
WITH T (row_num) AS
(SELECT ROW_NUMBER() OVER
(PARTITION BY a,b,c ORDER BY a,b,c,d,e)
FROM #Test)
DELETE FROM T
WHERE row_num > 1;
Google for "delete duplicates" and you'll find lots of other solutions
in the archives of this group.
Test it out and make sure you have a current backup first :-)
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||David,
sry, forgot that :) I'm using SQL 2000
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1147360308.771189.249980@.i40g2000cwc.googlegroups.com...
> Lasse Edsvik wrote:
a
that
the
unique.
and E
of
has
And
> Always tell us what version of SQL Server you are using.
> In SQL Server 2005:
> WITH T (row_num) AS
> (SELECT ROW_NUMBER() OVER
> (PARTITION BY a,b,c ORDER BY a,b,c,d,e)
> FROM #Test)
> DELETE FROM T
> WHERE row_num > 1;
> Google for "delete duplicates" and you'll find lots of other solutions
> in the archives of this group.
> Test it out and make sure you have a current backup first :-)
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||Hi Aaron,
consider raw data like this:
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,6)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,8)
then the query
SELECT A,B,C,MAX(D),MAX(E)
FROM table
GROUP BY A,B,C;
will produce a row
1,1,1,9,8
which is not present in the original data. Does it make sence?|||alter table #test add f timestamp
go
select * from #test
go
select A,B,C,D,E from #test where not exists(select 1 from #test t1
where t1.a=#test.a
and t1.b=#test.b
and t1.c=#test.c
and t1.f>#test.f)
A B C D E
-- -- -- -- --
1 1 1 -1 6
1 2 1 1 4
3 2 1 3 4
(3 row(s) affected)|||> which is not present in the original data. Does it make sence?
I don't know, I don't think the requirements were specific enough to make
you right or to make me wrong. I was just offering one possible solution.

Deleting Duplicate Data


Hi to All!
I have a table with 60 columns and more than one million rows. i have to
implement composite primary key but it gives me error of duplicate data.
i have used following query to detect the duplicate rows
select NID,output_No from tbl_Data
group by NID,output_No
having count(*) > 1
it gives me 2526 duplicate dows. Now i wants to delete the duplicate
rows what will be the query for deleting the duplicate records.
Thanx
*** Sent via Developersdex http://www.examnotes.net ***This script has written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Ghulam Farid" <gfaryd@.yahoo.com> wrote in message
news:umVO5durFHA.3444@.TK2MSFTNGP12.phx.gbl...
>
> Hi to All!
> I have a table with 60 columns and more than one million rows. i have to
> implement composite primary key but it gives me error of duplicate data.
> i have used following query to detect the duplicate rows
> select NID,output_No from tbl_Data
> group by NID,output_No
> having count(*) > 1
> it gives me 2526 duplicate dows. Now i wants to delete the duplicate
> rows what will be the query for deleting the duplicate records.
>
> Thanx
>
> *** Sent via Developersdex http://www.examnotes.net ***|||Try this:
(1) SELECT columnList INTO workTable FROM tableName GROUP BY keyColumns
HAVING COUNT(*) > 1
(2) DELETE tableName FROM workTable WHERE tableName.keyColumns =
workTable.keyColumns
(3) INSERT tableName (columnList) SELECT columnList FROM workTable
(4) DROP workTable
You might want to wrap this in a transaction, but if you don't then a temp
table for the work table is contraindicated because if power goes out
between steps 2 and 3, you will lose the duplicate rows altogether.
If the table were tiny, you could use something like:
SET ROWCOUNT 1
AGAIN:
DELETE tableName FROM (SELECT keyColumns FROM tableName GROUP BY keyColumns
HAVING COUNT(*) > 1) a WHERE tableName.keyColumns = a.keyColumns
IF @.@.ROWCOUNT > 0 GOTO AGAIN
SET ROWCOUNT 0
"Ghulam Farid" <gfaryd@.yahoo.com> wrote in message
news:umVO5durFHA.3444@.TK2MSFTNGP12.phx.gbl...
>
> Hi to All!
> I have a table with 60 columns and more than one million rows. i have to
> implement composite primary key but it gives me error of duplicate data.
> i have used following query to detect the duplicate rows
> select NID,output_No from tbl_Data
> group by NID,output_No
> having count(*) > 1
> it gives me 2526 duplicate dows. Now i wants to delete the duplicate
> rows what will be the query for deleting the duplicate records.
>
> Thanx
>
> *** Sent via Developersdex http://www.examnotes.net ***

Deleting duplicate data

Hello there
I've imported table without any unique key
The table have some duplicatate data on it. and i need to delete the
duplicate data
So far i had to alter the table and add unique field, and use it to delete
the duplicate records
Is there a way to do this without altering the table?
' 03-5611606
' 050-7709399
: roy@.atidsm.co.ilRoy Goldhammer wrote:
> Hello there
> I've imported table without any unique key
> The table have some duplicatate data on it. and i need to delete the
> duplicate data
> So far i had to alter the table and add unique field, and use it to delete
> the duplicate records
> Is there a way to do this without altering the table?
> --
> =F8=E5=F2=E9 =E2=E5=EC=E3=E4=EE=F8
> =F2=FA=E9=E3 =E4=F0=E3=F1=FA =FA=E5=EB=F0=E4
> =E8=EC' 03-5611606
> =F4=EC=E0' 050-7709399
> =E0=E9=EE=E9=E9=EC: roy@.atidsm.co.il
SELECT ...
INTO tmp
FROM your_table
GROUP BY keycol1, keycol2, keycol3
HAVING COUNT(*) > 1 ;
DELETE FROM your_table
WHERE EXISTS
(SELECT *
FROM tmp AS T
WHERE T.keycol1 =3D your_table.keycol1
AND T.keycol2 =3D your_tabkle.keycol2
AND T.keycol3 =3D your_tabkle.keycol3) ;
INSERT INTO yourtable (...)
SELECT ...
FROM tmp ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Roy
Please take a look at these examples written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Roy Goldhammer" <roy@.hotmail.com> wrote in message
news:OSv$5ruKGHA.1028@.TK2MSFTNGP11.phx.gbl...
> Hello there
> I've imported table without any unique key
> The table have some duplicatate data on it. and i need to delete the
> duplicate data
> So far i had to alter the table and add unique field, and use it to delete
> the duplicate records
> Is there a way to do this without altering the table?
> --
>
>
> ' 03-5611606
> ' 050-7709399
> : roy@.atidsm.co.il
>|||if number of rows are less than you can create temp table copy distinct
row in it, truncate main table and insert rows from temp table to main
table.
select * into temptable from (select distinct * from t1 ) a
truncate table t1
insert into t1 select * from temptable
drop table temptable.
else create identity column in the table and use it to delete data.
Regards
Amish Shahsql

Sunday, March 11, 2012

Deleteing duplicate records from my table

I just discovered that all my records appear twice inside my table, in
other words, they repeat on the row below. How can I delete all of the
duplicates? I'm sure there must be a tidy line of sql to do that.

Thanks,

Billbillzimmerman@.gospellight.com (Bill) wrote in message news:<8da5f4f4.0307310856.79830a8e@.posting.google.com>...
> I just discovered that all my records appear twice inside my table, in
> other words, they repeat on the row below. How can I delete all of the
> duplicates? I'm sure there must be a tidy line of sql to do that.
> Thanks,
> Bill

Maybe run a select distinct query and insert the results into a new
table? If need be, you could then delete all records from your
original table and insert the records back.

That should be reasonably tidy but it is hard to say what the
performance would look like without knowing the specifics.

deleteing duplicate records ?

Hi,
This is my table structure

Name Age

Siva 24
Siva 24
Raghu 25

In this above table siva 24 row is inserted twice . how to delete duplicate record .

If you use SQL Server 2005 the following query will help you..

WITH MYTABLE as (select *, Row_Number() over (order by Name,age) RowId from names)
Delete from MyTable Where Rowid Not in(Select Min(rowId) from MyTable Group By Name,Age);

If you use SQL Server 2000 you should have minimum one unique column (id) to remove the duplicates.

|||

One way (that works with both SQL 2000 and SQL 2005) is to create a new table, add the non-duplicate data to the new table, then drop the old table and rename the new table to the same name as the old table.

Here is a demonstration:

Code Snippet


SET NOCOUNT ON


CREATE TABLE MyTable
( [Name] varchar(25),
[Age] int
)
GO


INSERT INTO MyTable VALUES ( 'Siva', 24 )
INSERT INTO MyTable VALUES ( 'Siva', 24 )
INSERT INTO MyTable VALUES ( 'Raghu', 25 )


SELECT *
FROM MyTable

CREATE TABLE MyNewTable
( [Name] varchar(25),
[Age] int
)
GO


INSERT INTO MyNewTable
SELECT
[Name],
[Age]
FROM MyTable
GROUP BY
[Name],
[Age]
SELECT *
FROM MyNewTable
DROP TABLE MyTable
GO


EXECUTE sp_rename 'MyNewTable', 'MyTable'


SELECT *
FROM MyTable

|||

In this case we can simply use,

Code Snippet

Select Distinct Name, Age Into MyNewTable From MyTable;

Truncate Table MyTable;

Insert Into MyTable Select * From MyNewTable;

Drop Table MyNewTable;