How do I use ROW_NUMBER()?

前端 未结 13 2409
青春惊慌失措
青春惊慌失措 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:15

    Though I agree with others that you could use count() to get the total number of rows, here is how you can use the row_count():

    1. To get the total no of rows:

      with temp as (
          select row_number() over (order by id) as rownum
          from table_name 
      )
      select max(rownum) from temp
    2. To get the row numbers where name is Matt:

      with temp as (
          select name, row_number() over (order by id) as rownum
          from table_name
      )
      select rownum from temp where name like 'Matt'

    You can further use min(rownum) or max(rownum) to get the first or last row for Matt respectively.

    These were very simple implementations of row_number(). You can use it for more complex grouping. Check out my response on Advanced grouping without using a sub query

提交回复
热议问题