-2

I have a table where I have several cust_id duplicates. I would like to keep the row where prendate_next is nearest to the current date and delete the rest of the duplicates. Please help me how. I am new to this

cust_id     prendate_next
1000105737  2014-11-30 00:00:00.000
1000105836  2014-11-20 00:00:00.000
1000143646  2014-11-10 00:00:00.000
1000143646  2015-03-09 00:00:00.000
1000179487  2014-12-05 00:00:00.000
1000182253  2015-01-01 00:00:00.000
1000192740  2014-10-02 00:00:00.000
1000192740  2015-01-10 00:00:00.000
1000199419  2015-09-30 00:00:00.000
1000170578  2014-12-26 00:00:00.000
1000188890  2015-06-23 00:00:00.000
1000189075  2015-03-01 00:00:00.000
1000189075  2015-03-01 00:00:00.000
1000189144  2015-04-04 00:00:00.000
3
  • Do you have another unique id in this table? Commented Oct 8, 2014 at 15:19
  • 2
    duplicate: stackoverflow.com/questions/18256201/… Commented Oct 8, 2014 at 15:20
  • yes i do have an onther Commented Oct 8, 2014 at 15:23

1 Answer 1

1
;WITH cte AS (
    SELECT      cust_id, prendate_next,
                ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY ABS(DATEDIFF(DAY,prendate_next,GETDATE()))) AS RowNumber
    FROM        MyTable
)

DELETE MyTable
    FROM        MyTable
    INNER JOIN  cte         ON MyTable.cust_id = cte.cust_id
                            AND MyTable.prendate_next = cte.prendate_next
    WHERE       cte.RowNumber != 1

ABS(DATEDIFF(DAY,prendate_next,GETDATE())) counts how many days prendate_next is from today.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.