sql rank
We perform calculations on data using various aggregated functions such as Max, Min, and AVG. We get a single output row using these functions. SQL Sever provides SQL RANK functions to specify rank for individual fields as per the categorizations. It returns an aggregated value for each participating row. SQL RANK functions also knows as Window Functions.
我们使用各种汇总函数(例如最大,最小和AVG)对数据进行计算。 使用这些函数,我们得到一个输出行。 SQL Sever提供了SQL RANK函数,以根据分类为各个字段指定等级。 它为每个参与的行返回一个汇总值。 SQL RANK函数也称为窗口函数。
-
Note:
Windows term in this does not relate to the Microsoft Windows operating system. These are SQL RANK functions.
-
注意:
Windows术语与Microsoft Windows操作系统无关。
这些是SQL RANK函数。
We have the following rank functions.
我们具有以下等级函数。
-
ROW_NUMBER()
ROW_NUMBER()
-
RANK()
秩()
-
DENSE_RANK()
DENSE_RANK()
-
NTILE()
NTILE()
In the SQL RANK functions, we use the OVER() clause to define a set of rows in the result set. We can also use
SQL PARTITION BY
clause to define a subset of data in a partition. You can also use Order by clause to sort the results in a descending or ascending order.
在SQL RANK函数中,我们使用OVER()子句在结果集中定义一组行。 我们还可以使用
SQL PARTITION BY
子句在分区中定义数据的子集。 您也可以使用Order by子句对结果进行降序或升序排序。
Before we explore these SQL RANK functions, let’s prepare sample data. In this sample data, we have exam results for three students in Maths, Science and English subjects.
在探索这些SQL RANK函数之前,让我们准备示例数据。 在此样本数据中,我们获得了三个数学,科学和英语学科学生的考试成绩。
CREATE TABLE ExamResult
(StudentName VARCHAR(70),
Subject VARCHAR(20),
Marks INT
);
INSERT INTO ExamResult
VALUES
('Lily',
'Maths',
65
);
INSERT INTO ExamResult
VALUES
('Lily',
'Science',
80
);
INSERT INTO ExamResult
VALUES
('Lily',
'english',
70
);
INSERT INTO ExamResult
VALUES
('Isabella',
'Maths',
50
);
INSERT INTO ExamResult
VALUES
('Isabella',
'Science',
70
);
INSERT INTO ExamResult
VALUES
('Isabella',
'english',
90
);
INSERT INTO ExamResult
VALUES
('Olivia',
'Maths',
55
);
INSERT INTO ExamResult
VALUES
('Olivia',
'Science',
60
);
INSERT INTO ExamResult
VALUES
('Olivia',
'english',
89
);
We have the following sample data in the ExamResult table.
ExamResult表中包含以下示例数据。
Let’s use each SQL Rank Functions in upcoming examples.
让我们在接下来的示例中使用每个SQL Rank函数。
ROW_Number()SQL RANK函数
(
ROW_Number() SQL RANK function
)
We use ROW_Number() SQL RANK function to get a unique sequential number for each row in the specified data. It gives the rank one for the first row and then increments the value by one for each row. We get different ranks for the row having similar values as well.
我们使用ROW_Number()SQL RANK函数为指定数据中的每一行获取唯一的顺序号。 它为第一行赋予等级1,然后为每一行将值递增1。 对于具有相似值的行,我们得到的排名也不同。
Execute the following query to get a rank for students as per their marks.
执行以下查询以根据学生的分数获得其排名。
SELECT Studentname,
Subject,
Marks,
ROW_NUMBER() OVER(ORDER BY Ma