Link to home
Start Free TrialLog in
Avatar of svenkatapuram
svenkatapuram

asked on

Delete Records

I have one table in my database (Microsoft SQL server 6.5). It has primary key with two fields one with ID and the second called Number.

Example:

      RID           Number
      123           1
      123           2
      123           3
      123           4
      123           5
      123           6
      321           1
      321           2
      321           3
      321           4

I want to update the above records in such a way that i need to have only the highest 3 number records and i want to delete rest of the records. That means in the above case for RID 123 i need to keep 4, 5, 6 and delete the 1, 2, 3 Once i delete the records i need to update the 4, 5, 6 to 1, 2, 3.

Is there an easy way to do this in SQL like using stored procedure? (Without writing small prgram in VB using record sets etc.)

Thanks      
Avatar of TigerZhao
TigerZhao

delete from tableX t1 where (select count(t2.*) from tableX t2 where (t2.RID = t1.RID) and (t2.Number >= t1.Number)) > 3
Avatar of svenkatapuram

ASKER

i tried this it is not working
ASKER CERTIFIED SOLUTION
Avatar of samopal
samopal

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried this too.

But it is doing exactly opposite towhat i wanted to. That is it is deleting the records what ever i wanted (highest 3 records) and keeping the first ones.  

If you can help me you should get all the marks.
Thanks for helping me
sampol,

i tried by adding "not" after table name in the delete statement. The deleting is working fine.
Only update is doing in different way. If it has three rcords for the same id it is fine. But if it has only two records it is changing the number to 2, 3 rather than changing to 1, 2. Any way i can work out this one. Thanks once again for your help.
Ok, sorry for mistakes...
Try this one please

Delete from tableX t1 where t1.number+3 <= (Select max(t2.number) from tablex t2 where t1.RID=t2.RID)
select RID, Max(number) as MaxNumber, Count(number) as CountNumber from tablex Into #tmpB group by RID
Update tablex t1 set t1.number = t1.number - (Select maxNumber - CountNumber from #tmpB t2 where t1.RID=t2.RID)