Retrieving last record in each group from database - SQL Server 2005/2008

后端 未结 2 1689
误落风尘
误落风尘 2020-11-22 03:12

I have done some seaching by can\'t seem to get the results I am looking for. Basically we have four different management systems in place throughout our company and I am in

相关标签:
2条回答
  • 2020-11-22 03:32
    ;with cteRowNumber as (
        select COMPUTERNAME, SERIALNUMBER, USERNAME, LASTIP, LASTUPDATE, SOURCE,
               row_number() over(partition by COMPUTERNAME order by LASTUPDATE desc) as RowNum
            from YourTable
    )
    select COMPUTERNAME, SERIALNUMBER, USERNAME, LASTIP, LASTUPDATE, SOURCE
        from cteRowNumber
        where RowNum = 1
    
    0 讨论(0)
  • 2020-11-22 03:53

    In SQL Server, the most performant solution is often a correlated subquery:

    select t.*
    from t
    where t.lastupdate = (select max(t2.lastupdate)
                          from t t2
                          where t2.computername = t.computername
                         );
    

    In particular, this can take advantage of an index on (computername, lastupdate). Conceptually, the reason this is faster than row_number() is because this query simply filters out the rows that don't match. The row_number() version needs to attach to the row number to all rows, before it filters -- that is more data processing.

    0 讨论(0)
提交回复
热议问题