Purging duplicate records?

Posted on 2006-05-04
Last Modified: 2006-11-18
I have a table with three fields:

Item        varchar(4)
Customer  varchar(4)
price        smallmoney

sometimes there are more than one matching record. A matching record is when (item + customer) is the same.

Is there a way to eliminate all the duplicates besides for the last one. The last one would be the one that was added to the table last. This table is a temporary table with no indexes.
Question by:szx248
    LVL 75

    Expert Comment

    by:Aneesh Retnakaran
    ALTER your temp table to add an identity column 'i'

    delete from #tempTable
    WHERE i NOT IN (SELECT MAX(i) FROM #tempTable GROUP BY (item + customer) )

    Author Comment

    Very neat!

    Now do I give the temporary table an identity column?

    this is what my temporary table looks like:
     CREATE TABLE #tempfile ( cus varchar(4), item varchar(4) , price smallmoney)
    LVL 75

    Accepted Solution

    CREATE TABLE #tempfile ( i int identity , cus varchar(4), item varchar(4) , price smallmoney)

    Author Comment


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    The steps for moving the system databases to a new location are documented in the following technical article: However sometimes after the moving process is finished, though SQL i…
    JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
    Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
    Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now