我想根据排序的排名从下表中选择名称,其中rank =排名最高的排名
如下表所示,结果将是
| 6| r | 1
获得此记录后,我将显示给用户,然后点击一些按钮,我将其移动到另一个表,然后用户询问下一组结果,然后下一个结果将是
| 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
我尝试使用两个select语句,首先我将在排序后获得最高排名
按排名desc
从标签顺序中选择前1 @ toprank =排名然后是第二次
从选项卡中选择名称,其中rank = @ toprank
但我想在一个声明中这样做,因为记录是数百万。
答案 0 :(得分:1)
首先关闭SELECT
要显示给用户的记录:
SELECT * FROM [YOUR_TABLE]
WHERE Rank = (SELECT TOP 1 Rank FROM [YOUR_TABLE] ORDER BY Rank)
这将返回一个或多个排名最高的行,您可以将这些行显示给用户,作为即将删除/移动的记录。
假设您要存储返回给用户的Rank
,则可以将其用作删除和放大器中的参数。移动/存档操作。
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
答案 1 :(得分:0)
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
结果首次运行:
ID name Rank
6 r 1
结果第二次运行:
ID name Rank
4 v 5
4 K 5