How do I use ROW_NUMBER()?

前端 未结 13 2378
青春惊慌失措
青春惊慌失措 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:27
    select 
      Ml.Hid,
      ml.blockid,
      row_number() over (partition by ml.blockid order by Ml.Hid desc) as rownumber,
      H.HNAME 
    from MIT_LeadBechmarkHamletwise ML
    join [MT.HAMLE] h on ML.Hid=h.HID
    
    0 讨论(0)
  • 2020-11-28 03:29

    ROW_NUMBER() returns a unique number for each row starting with 1. You can easily use this by simply writing:

    ROW_NUMBER() OVER (ORDER BY 'Column_Name' DESC) as ROW_NUMBER
    
    0 讨论(0)
  • 2020-11-28 03:30

    You can use Row_Number for limit query result.

    Example:

    SELECT * FROM (
        select row_number() OVER (order by createtime desc) AS ROWINDEX,* 
        from TABLENAME ) TB
    WHERE TB.ROWINDEX between 0 and 10
    

    -- With above query, I will get PAGE 1 of results from TABLENAME.

    0 讨论(0)
  • 2020-11-28 03:31

    For the first question, why not just use?

    SELECT COUNT(*) FROM myTable 
    

    to get the count.

    And for the second question, the primary key of the row is what should be used to identify a particular row. Don't try and use the row number for that.


    If you returned Row_Number() in your main query,

    SELECT ROW_NUMBER() OVER (Order by Id) AS RowNumber, Field1, Field2, Field3
    FROM User
    

    Then when you want to go 5 rows back then you can take the current row number and use the following query to determine the row with currentrow -5

    SELECT us.Id
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY id) AS Row, Id
         FROM User ) us 
    WHERE Row = CurrentRow - 5   
    
    0 讨论(0)
  • 2020-11-28 03:31

    This query:

    SELECT ROW_NUMBER() OVER(ORDER BY UserId) From Users WHERE UserName='Joe'
    

    will return all rows where the UserName is 'Joe' UNLESS you have no UserName='Joe'

    They will be listed in order of UserID and the row_number field will start with 1 and increment however many rows contain UserName='Joe'

    If it does not work for you then your WHERE command has an issue OR there is no UserID in the table. Check spelling for both fields UserID and UserName.

    0 讨论(0)
  • 2020-11-28 03:32

    You can use this for get first record where has clause

    SELECT TOP(1) * , ROW_NUMBER() OVER(ORDER BY UserId) AS rownum 
    FROM     Users 
    WHERE    UserName = 'Joe'
    ORDER BY rownum ASC
    
    0 讨论(0)
提交回复
热议问题