Maison > base de données > tutoriel mysql > le corps du texte

Sqlserver使用排名函数Row_Number()函数查询指定范围的数据

WBOY
Libérer: 2016-06-07 17:40:37
original
1524 Les gens l'ont consulté

在数据库中有一数据表Student,字段有StudentID,StudentName,ClassID,其中StudentID并不是连续的编号,现在的任务是查询出指定范围内的数据,比如想要查询第五条数据和第十条数据。如果StudentID为连续的编号,那么这个任务会简单些。对于不连续的编号,

在数据库中有一数据表Student,字段有StudentID,StudentName,ClassID,其中StudentID并不是连续的编号,现在的任务是查询出指定范围内的数据,比如想要查询第五条数据和第十条数据。如果StudentID为连续的编号,那么这个任务会简单些。对于不连续的编号,我们可以使用Row_Number函数,使用该函数对数据行进行排序,然后根据生成的排序号对数据进行筛选。

具体的步骤为:

1.首先使用Row_Number函数对数据添加排序

 select StudentID,StudentName,ClassID,Row_Number() OVER(Order by StudentID) AS 'RowNumber'

from Student

注意这里的Row_Number函数必须要有Order By字段,Partition By字段可选。这一步完成之后,就会增加一列“RowNumber”,为连续的。

2.使用第一步产生的表作为基表,香港虚拟主机,结合Between..And..函数来完成对指定范围内的数据进行查询

select *

from(select StudentID,StudentName,ClassID,香港服务器租用,Row_Number() OVER(Order by StudentID) AS 'RowNumber'

          from Student

      ) as OrderStudent

where RowNumber between 5 and 10

通过这个步骤会查询出经过排名之后的第五到第十(包括第五和第十)条数据。

根据上面的分析,我们可以很容易扩展,假如我要查询每个分组的前N项数据行:使用Row_number的pattition by字段对数据进行分组,并排名,挑选出每组排名小于N的数据行即可。

具体的SQL语句为:

select * from (select *,Row_Number() OVER (Partiton By ClassID Order by StudentID) as "RowNumber") as OrderedData

where RowNumber 

首先对数据表进行分组并对每一个小组进行排名,虚拟主机,然后选择每个小组中排名小于指定的N即可。 

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!