Search code examples
sqlsql-server-2008selectlast-modified

SQL: How to make a query that return last created row per each user from table's data


Consider following table's data

ID      UserID  ClassID SchoolID    Created
2184    19313   10      28189       2010-10-25 14:16:39.823
46697   19313   10      27721       2011-04-04 14:50:49.433
•47423  19313   11      27721       2011-09-15 09:15:51.740
•47672  19881   11      42978       2011-09-19 17:31:12.853
3176    19881   11      42978       2010-10-27 22:29:41.130
22327   19881   9       45263       2011-02-14 19:42:41.320
46661   32810   11      41861       2011-04-04 14:26:14.800
•47333  32810   11      51721       2011-09-13 22:43:06.053
131     32810   11      51721       2010-09-22 03:16:44.520

I want to make a sql query that return the last created row for each UserID in which the result will be as below ( row that begin with in the above rows ) :

ID      UserID  ClassID SchoolID    Created
47423   19313   11      27721       2011-09-15 09:15:51.740
47672   19881   11      42978       2011-09-19 17:31:12.853
47333   32810   11      51721       2011-09-13 22:43:06.053

Solution

  • You can use a CTE (Common Table Expression) with the ROW_NUMBER function:

    ;WITH LastPerUser AS
    (
       SELECT 
           ID, UserID, ClassID, SchoolID, Created,
           ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY Created DESC) AS 'RowNum')
       FROM dbo.YourTable
    )
    SELECT 
       ID, UserID, ClassID, SchoolID, Created,
    FROM LastPerUser
    WHERE RowNum = 1
    

    This CTE "partitions" your data by UserID, and for each partition, the ROW_NUMBER function hands out sequential numbers, starting at 1 and ordered by Created DESC - so the latest row gets RowNum = 1 (for each UserID) which is what I select from the CTE in the SELECT statement after it.