MSSQL2000 排序问题很急,大家帮忙!
发布网友
发布时间:2023-01-05 00:12
我来回答
共4个回答
热心网友
时间:2023-06-26 02:41
CREATE TABLE t_User (
id int IDENTITY(1,1) PRIMARY KEY,
u_Mun int,
u_Top int
);
INSERT INTO t_User
SELECT 1, 0 UNION ALL
SELECT 3, 0 UNION ALL
SELECT 5, 0 UNION ALL
SELECT 2, 0 UNION ALL
SELECT 4, 0 UNION ALL
SELECT 6, 0;
GO
DECLARE
@i INT,
@Mun INT,
@Top INT;
BEGIN
-- 定义游标.
DECLARE c_test_main CURSOR FOR
SELECT u_Mun, u_Top FROM t_User ORDER BY u_Mun DESC
FOR UPDATE;
-- 打开游标.
OPEN c_test_main;
SET @i = 0;
WHILE 1=1
BEGIN
-- 填充数据.
FETCH NEXT FROM c_test_main INTO @Mun, @Top;
-- 假如未检索到数据,退出循环.
IF @@fetch_status != 0 BREAK;
SET @i = @i + 1;
UPDATE t_User SET u_Top = @i WHERE CURRENT OF c_test_main;
END;
-- 关闭游标
CLOSE c_test_main;
-- 释放游标.
DEALLOCATE c_test_main;
END
GO
1> select * from t_User;
2> go
id u_Mun u_Top
----------- ----------- -----------
1 1 6
2 3 4
3 5 2
4 2 5
5 4 3
6 6 1
(6 行受影响)
热心网友
时间:2023-06-26 02:42
Declare @idx int--保存名次
Declare @UserID nvarchar(50)--保存用户ID
Declare @Mun INT--保存积分
Declare @mcur cursor
SET @idx=0
set @mcur=cursor for
select t_UserID,u_Mun
from t_User
order by autoid
open @mcur
FETCH NEXT FROM @mcur INTO @UserID,@Mun
WHILE (@@FETCH_STATUS=0)
BEGIN
SET @idx=@idx+1
update t_User SET u_Top=@idx where t_UserID=@UserID
FETCH NEXT FROM @mcur INTO @UserID,@Mun
End
close @mcur--关闭游标
DEALLOCATE @mcur--释放游标
热心网友
时间:2023-06-26 02:42
为什么要保存这个名次呢?
你还不如按照这个排序输出结果,然后定义一个i=1,循环一次i=i+1,输出名次的同时,也输出i,不是更好?
还能动态、准确的显示名次!!!
望采纳!!
热心网友
时间:2023-06-26 02:43
更新的时候需要用到一个ID字段,你根据你的表结构改下u_id就可以
UPDATE t_User
SET u_Top = b.paim
FROM (SELECT u_id,
RANK() OVER(ORDER BY u_Mun desc) AS paim
FROM t_User) b
WHERE t_User.u_id = b.u_id