How do I use ROW_NUMBER()?

前端 未结 13 2462
青春惊慌失措
青春惊慌失措 2020-11-28 02:35

I want to use the ROW_NUMBER() to get...

  1. To get the max(ROW_NUMBER()) --> Or i guess this would also be the count of all rows
13条回答
  •  臣服心动
    2020-11-28 03:18

    SQL Row_Number() function is to sort and assign an order number to data rows in related record set. So it is used to number rows, for example to identify the top 10 rows which have the highest order amount or identify the order of each customer which is the highest amount, etc.

    If you want to sort the dataset and number each row by seperating them into categories we use Row_Number() with Partition By clause. For example, sorting orders of each customer within itself where the dataset contains all orders, etc.

    SELECT
        SalesOrderNumber,
        CustomerId,
        SubTotal,
        ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY SubTotal DESC) rn
    FROM Sales.SalesOrderHeader
    

    But as I understand you want to calculate the number of rows of grouped by a column. To visualize the requirement, if you want to see the count of all orders of the related customer as a seperate column besides order info, you can use COUNT() aggregation function with Partition By clause

    For example,

    SELECT
        SalesOrderNumber,
        CustomerId,
        COUNT(*) OVER (PARTITION BY CustomerId) CustomerOrderCount
    FROM Sales.SalesOrderHeader
    

提交回复
热议问题