aspx Tutorial

.NET Articles,jQuery demo, asp.net with jQuery, online tutorial,Jquery, SilverLight, Javascript, asp.net,JSON, MVC,.NET Articles,demo, Web Services, .NET articles, Sharepoint 2010, visual studio 2010,Aamir Hasan,IT
Advertise Here

Advertize

wwwSW
Posted by Aamir Hasan   on Saturday, June 26, 2010 Total Views:  

In this Article, i will tell you some technique that how can we delete a duplicate rows from a table. Why this duplicate values exist in table it mean that a problem is in the code logic and table desgin. Read database normalization to correct the structure of your database. Let's Design the table structure called  Patient Table. And insert some data.

Select duplicate rows from a Patient Table with  primary key in a table

Check if Patient table exists in the database then drop it and create it.

 

IF OBJECT_ID('PATIENT') IS NOT NULL
    DROP TABLE PATIENT
CREATE TABLE PATIENT
    (
      ID BIGINT IDENTITY NOT NULL PRIMARY KEY,
      FULLNAME NVARCHAR(MAX) ,
      CCID BIGINT ,
      AGE INT ,
      GENDER CHAR(10) ,
      BIRTHDAY SMALLDATETIME ,
      REGISTATIONDATETIME DATETIME ,
      ISDELETED BIT DEFAULT ( 0 )
    )

 

 

INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 101, 23, 'MALE', '1990-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AMIR ALI', 102, 23, 'MALE', '1993-02-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AHMED ALI', 103, 23, 'FEMALE', '1994-08-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'SONIA KHAN', 104, 23, 'FEMALE', '1991-07-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AWAIS AHMED', 105, 23, 'MALE', '1992-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR KHAN', 106, 23, 'MALE', '1997-01-05', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'SOBIA HINA', 107, 23, 'FEMALE', '1988-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'ADNAN KHAN', 106, 23, 'MALE', '1987-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 108, 23, 'MALE', '1997-04-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 101, 23, 'MALE', '1990-01-01', GETDATE(), 0 )

 

 

Now you have notice that some duplicate values are loaded in Patient table. Select Duplicate records from a Patient Table

SELECT  *
        FROM patient
WHERE   ID NOT IN ( SELECT  MAX(ID)
                    FROM    patient
                    GROUP BY fullname )

Delete Duplicate Rows From a Patient Table as you see in below Query

DELETE
        FROM patient
WHERE   ID NOT IN ( SELECT  MAX(ID)
                    FROM    patient
                    GROUP BY fullname )

Above Query has deleted those Patient records who have duplicate CCID Number. Now, Select all Patient Table records to verify that all duplicate records deleted.

SELECT  *
FROM    patient

Another way to Select and delete Duplicate rows from a table

Select patient id which have duplicate rows

 

SELECT  *
FROM    ( SELECT    id ,
                    row_number() OVER ( PARTITION BY ccid ORDER BY ccid ) AS dupid
          FROM      patient
        ) temp1
WHERE   temp1.dupid >= 2

Delete rows which have duplicate rows

DELETE  FROM patient
WHERE   id IN (
        SELECT  id
        FROM    ( ( SELECT  id ,
                            row_number() OVER ( PARTITION BY ccid ORDER BY ccid ) AS dupid
                    FROM    patient
                  )
                )temp1
        WHERE   temp1.dupid >= 2 )

 

 

Another way to Select and delete Duplicate rows from a table using Temporary Table

 

SELECT  id ,
                row_number() OVER ( PARTITION BY ccid ORDER BY ccid ) AS dupid
        INTO    #temptable
        FROM    patient
       
        SELECT  *
        FROM    patient
        WHERE   id IN ( SELECT  id
                        FROM    #temptable )

 

 

Select duplicate rows from  a table using common table expression

 

WITH    duplicateCCID
          AS ( SELECT   id ,
                        row_number() OVER ( PARTITION BY ccid ORDER BY ccid ) AS dupid
               FROM     patient
             )
    SELECT  *
    FROM    duplicateCCID
    WHERE   dupid >= 2 

delete duplicate rows from a table using common table expression (CTE)

WITH    duplicateCCID
          AS ( SELECT   id ,
                        row_number() OVER ( PARTITION BY ccid ORDER BY ccid ) AS dupid
               FROM     patient
             )
    DELETE
    FROM    duplicateCCID
    WHERE   dupid >= 2

 

 

Select duplicate rows from a Patient Table with no primary key in a table

Below query define Common Table Expression (CTE). i have used DENSE_RANK() function to group the records based on CCID Column

IF OBJECT_ID('PATIENT') IS NOT NULL
    DROP TABLE PATIENT
CREATE TABLE PATIENT
    (
    
      FULLNAME NVARCHAR(MAX) ,
      CCID BIGINT ,
      AGE INT ,
      GENDER CHAR(10) ,
      BIRTHDAY SMALLDATETIME ,
      REGISTATIONDATETIME DATETIME ,
      ISDELETED BIT DEFAULT ( 0 )
    )

INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 101, 23, 'MALE', '1990-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AMIR ALI', 102, 23, 'MALE', '1993-02-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AHMED ALI', 103, 23, 'FEMALE', '1994-08-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'SONIA KHAN', 104, 23, 'FEMALE', '1991-07-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AWAIS AHMED', 105, 23, 'MALE', '1992-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR KHAN', 106, 23, 'MALE', '1997-01-05', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'SOBIA HINA', 107, 23, 'FEMALE', '1988-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'ADNAN KHAN', 106, 23, 'MALE', '1987-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 108, 23, 'MALE', '1997-04-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR HASAN', 101, 23, 'MALE', '1990-01-01', GETDATE(), 0 )
INSERT  INTO PATIENT
VALUES  ( 'AAMIR KHAN', 107, 23, 'MALE', '1990-01-01', GETDATE(), 0 )

 

WITH    PatientCTE
          AS ( SELECT   * ,
                        RANKING = DENSE_RANK() OVER ( PARTITION BY CCID ORDER BY NEWID() ASC )
               FROM     PATIENT
             )
    SELECT  *
    FROM    PatientCTE
    WHERE   RANKING >= 2

 


 

Another Way

 

WITH    PatientCTP
          AS ( SELECT   DupID = ROW_NUMBER() OVER ( PARTITION BY ccID ORDER BY ( SELECT
                                                              1
                                                              ) ) ,
                        *
               FROM     patient
             )
    SELECT  *
    FROM    PatientCTP
    WHERE   dupid >= 2
    ORDER BY ccid

 

Delete Duplicate Rows from a Patient Table with no Primary Key

 

WITH    PatientCTE
          AS ( SELECT   * ,
                        RANKING = DENSE_RANK() OVER ( PARTITION BY CCID ORDER BY NEWID() ASC )
               FROM     PATIENT
             )
    DELETE  FROM PatientCTE
    WHERE   RANKING >= 2

 

 

I have used Common Table Expression to Select and Delete Duplicate records from a Paitent Table. Common Table Expression is Virtual Table. I have deleted records from the PatientCTE that have Ranking greater then and eqwal to 2. Above Query will remove  all duplicate records.

Now Select the all Patient records to verify it that duplicate rows a re deleted.

 

Download

Delete Duplicate rows With Primary Key.sql (1.79 kb)

Delete Duplicate rows With Primary Key.sql (1.79 kb)

Tags:
Category: All | MS SQL | SQL 2008
Protected by Copyscape Online Plagiarism Tool

Comments (19) -

buy wow gold
buy wow gold United States
10/22/2010 1:01:18 AM #

Great articles & Nice a site!!

loewe handbags
loewe handbags United States
11/3/2010 11:26:25 PM #

pocket that is lined This bag is Convenient stylish and roomy

lv bags
lv bags United States
11/4/2010 8:16:55 PM #

will choose to own a used genuine Hermes accessories It wasnt until

fendi handbags
fendi handbags United States
11/8/2010 10:56:49 AM #

Burberry item of any sort then you stop this monster But the question

miumiu
miumiu United States
11/8/2010 2:07:55 PM #

want to make your final selection played up by these dominant

valentino handbags
valentino handbags United States
11/12/2010 8:51:56 PM #

really loved the look of these two prominently displayed on the front

gucci handbags
gucci handbags United States
11/14/2010 2:40:02 PM #

online stores that carry different expensive handbags that you find in

wow gold
wow gold United States
11/18/2010 7:01:45 PM #

to Garbadia dictator wow gold ancient to the best of each

replica gucci
replica gucci United States
11/21/2010 1:05:47 PM #

culturally fitted clothes watches jewelry headquarters in Paudex/Le Brassus This company

ffxiv gold
ffxiv gold United States
11/21/2010 1:12:25 PM #

magic Huang power to always been highly valued by a

replica tissot
replica tissot United States
11/24/2010 8:10:37 PM #

watches can be produced in one year In order to time and you are good at finding good items in low

audemars piguet watches
audemars piguet watches United States
11/28/2010 11:19:11 AM #

to make a loyal customer or a Montblonc collector figure is just a reflection of the importance this

AZ Pool Remodeling
AZ Pool Remodeling United States
2/23/2011 8:28:07 PM #

I will bookmark this site

Mlb jerseys wholesale
Mlb jerseys wholesale United States
5/17/2011 9:57:19 PM #

Really fascinating subject, I will bookmark your website to check if you write more in the future. Kind regards,

CR Lithium battery
CR Lithium battery United States
6/8/2011 11:57:54 PM #

Terrific Blog. then the simillar post I found last Tuesday online. Your business plan should describe in detail your management team with biographies of your principal team members.

penis enlargement
penis enlargement United States
10/24/2011 4:47:24 AM #

great post.. i really enjoyed it

ferragamo shoes sale
ferragamo shoes sale People's Republic of China
1/3/2012 8:44:27 PM #

<a href="http://www.cheapghdsalesuk.co.uk">GHD straighteners UK</a> is incredibly popular, and the collectable nature of these beautiful pieces of means that many people are searching for them online. As with any designer label, there will always be companies selling <a href="http://www.cheapghdsalesuk.co.uk">cheap GHD Straighteners</a>, however when you are buying online how can you be sure that what you are purchasing is the genuine . If you are buying directly from the official <a href="http://www.cheapghdsalesuk.co.uk">ghd hair straighteners uk</a>, then you are of course going to be getting the real deal.  If you have not yet tried <a href="http://www.hotbuybags.com/">replica  handbags wholesale</a>, it's time to own one and feel the difference it can  make to your personality.
These <a href="www.hotbuybags.com/loewe-handbags">replica Loewe Handbags</a> would be nice investments for you in long term.
One of  things appreciated by it's fans is the versatility of <a href="www.hotbuybags.com/loewe-handbags">Loewe Handbags replica</a>.
Just in the range of <a href="www.hotbuybags.com/marc-jacobs-handbags">Marc Jacobs Handbags  replica</a>, it provides options of a standard or you could opt for the obsidian.
These <a href="www.hotbuybags.com/mulberry-handbags">replica Mulberry Handbags</a> are brilliant and prove to be wonderful for you while it makes you stand out of  the crowd.
These are just brilliant and fabulous <a href="www.hotbuybags.com/gucci-handbags">replica Gucci Handbags</a>.

solar power systems
solar power systems Islamic Republic of Pakistan
1/10/2012 1:39:22 AM #

I am really inspired from your blog, I must say you have done a terrific job.
www.greenbiz.com.pk/solar_pv_panel_pk_res.php

Christian Louboutin Shoes Sale
Christian Louboutin Shoes Sale People's Republic of China
1/10/2012 9:04:27 PM #

Know a lot of brand shoes, the most favorite brand is http://www.pumpshome.com/ Christian Louboutin Shoes Sale, red soles creative, wearing http://www.pumpshome.com/ Cheap Louboutin Wedding Shoes wedding is very much looking forward to be married the girl thing. http://www.pumpshome.com/ Christian Louboutin On Sale a new product will cause buying spree!
http://www.pumpshome.com/categories-pumps.html Christian Louboutin Pumps Black
http://www.pumpshome.com/categories-boots.html Christian Louboutin Boots On Sale
http://www.pumpshome.com/categories-for-men.html Christian Louboutin Mens
http://www.pumpshome.com/categories-sneakers.html christian louboutin high top sneakers
http://www.pumpshome.com/categories-flats.html christian louboutin flats for cheap
http://www.pumpshome.com/manolo-blahnik.html manolo blahnik something blue shoes
http://www.pumpshome.com/salvatore-ferragamo.html ferragamo shoes outlet
http://www.pumpshome.com/ysl-shoes.html ysl tribute sale

tigerly
tigerly People's Republic of China
3/8/2012 11:01:26 PM #

Apparels play a significant role in enhancing ones [url=http://www.hollister-online.co.uk/]hollister UK outlet[/url] and that is why people want to dress up smart and look good. There are many designer wears that are available and each company is trying to come up with their own range of clothing. These include men’s wear, women’s wear, and even kids wear. [url=http://www.hollistersale-uk.co.uk/]hollister outlet[/url] is one of the well known companies that are promoting casual wear and coming up with trendy new designs. Established in 1892, [url=http://www.abercrombieandfitchsale-ukoutlet.co.uk/]abercrombie sale[/url] has been manufacturing quality apparels for men, women, and kids alike. Some of [url=http://www.hollistergonewsale.co.uk/]hollister UK[/url] the well know apparels from the Abercrombie are abercrombie t-shirts, [url=http://www.hollisteronline.co.uk/]hollister sale[/url], [url=http://www.abercrombieandfitchsale-ukoutlet.co.uk/]Abercrombie and Fitch outlet[/url], abercrombie hoodies, including many others.

fafafa
fafafa Slovenia
4/23/2012 3:06:59 AM #

http://www.christianlouboutinukk.org   christian louboutin
http://www.tiffanyuks.org   tiffany uk
http://www.gucciukbeltuk.org   gucci belt
http://www.frsaclouisvuittonsac.com   louis vuitton sac
http://www.chanelukoutletuks.org   chanel outlet
http://www.burberryukoutletuk.org   burberry
http://www.poloralphlaurenuko.org   ralph lauren uk

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Advertizement 1
Advertizement 2
Advertizement 3
Advertizement 4
Advertizement 5