温馨提示×

row_number()在SQL Server中的应用示例有哪些

sql
小樊
91
2024-08-17 23:17:36
栏目: 云计算

  1. 使用row_number()函数为查询结果集中的每一行分配一个唯一的行号,常用于分页查询中。例如:
SELECT 
    ROW_NUMBER() OVER (ORDER BY ProductID) AS RowNum,
    ProductID,
    ProductName,
    UnitPrice
FROM Products
  1. 可以结合PARTITION BY子句将结果集分组,每个分组从1开始计数。例如:
SELECT 
    ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ProductID) AS RowNum,
    ProductID,
    ProductName,
    CategoryID
FROM Products
  1. 使用row_number()函数来查找每个分组中的前N个记录。例如,以下查询将在每个类别中找到前两个产品:
SELECT 
    *
FROM (
    SELECT 
        ProductID,
        ProductName,
        CategoryID,
        ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ProductID) AS RowNum
    FROM Products
) AS RankedProducts
WHERE RowNum <= 2
  1. 可以在row_number()函数中使用ORDER BY子句来指定排序规则。例如,以下查询按UnitPrice从高到低对产品进行排序:
SELECT 
    ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS RowNum,
    ProductID,
    ProductName,
    UnitPrice
FROM Products

0