欢迎来到代码驿站!

MsSql

当前位置:首页 > 数据库 > MsSql

SQLServer RANK() 排名函数的使用

时间:2022-12-17 09:50:21|栏目:MsSql|点击:

本文主要介绍了SQLServer RANK() 排名函数的使用,具体如下:

-- 例子表数据
SELECT * FROM test;
-- 统计分数
SELECT name,SUM(achievement) achievement FROM test GROUP BY name; 
-- 按统计分数做排行
SELECT RANK() OVER( ORDER BY SUM(achievement) desc) 排行,name,SUM(achievement) achievement FROM test GROUP BY name;

求助问答存储过程使用:

USE [DB]
GO
 
/****** Object:  StoredProcedure [dbo].[sp_TodayJoinUser]    Script Date: 2021/1/26 14:45:24 ******/
SET ANSI_NULLS ON
GO
 
SET QUOTED_IDENTIFIER ON
GO
 
 
-- =============================================
-- Author:		_Hey_Jude
-- Create date: 2021-01-26
-- Description:	获取今日发表帮助/回复的新用户
-- =============================================
CREATE PROCEDURE [dbo].[sp_TodayJoinUser] 
	@tableLevel int,
    @date varchar(30)
AS
Declare @Sql nvarchar(max) 
declare @minTabId int
declare @maxTabId int
declare @maxf_id int
declare @helpTableName nvarchar(max)
declare @tableCount int
 
BEGIN
	 --最小f_id所在表
	 set @minTabId=0
	 set @tableCount=@minTabId
	 --最大f_id所在表
	 set @maxf_id=(select MAX(F_ID) from [Table] where F_IsDelete=0)
	 set @maxTabId=@maxf_id/@tablelevel
 
	 set @helpTableName='SELECT UserID, Max([F_DateTime]) AS dt FROM [Table] GROUP BY UserID'
 
	 while @tableCount<=@maxTabId
	 begin		
		print @tableCount
		set @helpTableName += ' UNION SELECT UserID, Max([DateTime]) as dt FROM SubTable'+cast(@tableCount as nvarchar(10))+' GROUP BY UserID '
		set @tableCount=@tableCount+1
	 end 
	          
     set @Sql='SELECT [nikename] FROM ( 
					SELECT UserID, RANK() OVER(PARTITION BY UserID ORDER BY dt) AS Num,dt FROM ( '+@helpTableName+' ) AS T ) AS NewT
			   LEFT JOIN [UserTable] A WITH(NOLOCK) ON NewT.UserID = A.UserId WHERE Num = 1 AND dt > '''+@date+''''
 
	 Exec sp_executesql @Sql
END
 
GO

partition的意思是对数据进行分区,sql语句如下

SELECT* FROM (
    SELECT
        ROW_NUMBER() over(partition by [姓名] order by [打卡时间] desc) as rowNum,
        [姓名],
        [打卡时间]
    FROM [dbo].[打卡记录表]
    ) temp
WHERE temp.rowNum = 1

通过 partition by [姓名] order by [打卡时间] desc,这句就可以做到,让数据按照姓名分组,并且在每组内部按照时间进行排序

上一篇:SQL Server中索引的用法详解

栏    目:MsSql

下一篇:没有了

本文标题:SQLServer RANK() 排名函数的使用

本文地址:http://www.codeinn.net/misctech/221548.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有