Domanda

I want to select name from a below table based on sorted rank and where rank = top most rank

like for below table, results would be

| 6| r          | 1  

after getting this record , I will display to user and then on some button click, I move it to another table and then user ask next set of results then next result would be

| 4| v          | 5 

| 7| K          | 5       ---added this line


|ID| name       | Rank

| 2| a          | 88   
| 3| b          | 56   
| 8| t          | 12   
| 1| c          | 45   
| 4| v          | 5 
| 7| K          | 5 -- ADDED THIS LINE  
| 5| d          | 11    
| 6| r      | 1     

I tried using two select statement , where in first I will get top rank after sorting it

select top 1 @toprank= rank from tab order by rank desc

and then secondly

select name from tab where rank=@toprank

but i want to do it in a single statement because records are in millions.

È stato utile?

Soluzione

create table test(ID int, name char(1), Rank int)
insert test values
(2,'a',88 ),(3,'b',56),(6,'t',12),(1,'c',45),
(4,'v',5),(4,'K',5),(5,'d',11),(6,'r',1)    

;with cte as
(
  -- if you only want 1 row at a time, exclude 'with ties'
  select top 1 with ties ID, name, Rank
  from test
  order by rank
)
delete 
from cte
output deleted.ID, deleted.name, deleted.Rank

Result first run:

ID  name  Rank
6   r     1

Result second run:

ID  name  Rank
4   v     5
4   K     5

Altri suggerimenti

So first off SELECT the records you want to display to the user:

SELECT * FROM [YOUR_TABLE] 
WHERE Rank = (SELECT TOP 1 Rank FROM [YOUR_TABLE] ORDER BY Rank)

This will return one or many rows with the highest rank that you can display to the user as the records that are about to be deleted/moved.

Assuming you are storing the Rank that is returned to the user, you can then use this as a parameter in your delete & move/archive operation.

DECLARE @Rank int
SET @Rank = 1 -- this would be passed in to the procedure

-- MOVE DATA
INSERT INTO [YOUR_ARCHIVE_TABLE] (ID, Name, Rank)
(SELECT ID, Name, Rank FROM [YOUR_TABLE] WHERE Rank = @Rank)

--DELETE DATA
DELETE FROM [YOUR_TABLE]
WHERE Rank = @RankToDelete
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top