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      
svenkatapuramAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
samopalConnect With a Mentor Commented:
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 from tablex Into #tmpB group by RID
Update tablex t1 set t1.number = t1.number - (Select maxNumber from #tmpB t2 where t1.RID=t2.RID) + 3
0
 
TigerZhaoCommented:
delete from tableX t1 where (select count(t2.*) from tableX t2 where (t2.RID = t1.RID) and (t2.Number >= t1.Number)) > 3
0
 
svenkatapuramAuthor Commented:
i tried this it is not working
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
svenkatapuramAuthor Commented:
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
0
 
svenkatapuramAuthor Commented:
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.
0
 
samopalCommented:
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)
0
All Courses

From novice to tech pro — start learning today.