简体   繁体   English

SQL:如何进行查询以返回每个用户从表数据中最后创建的行

[英]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 ) : 我想执行一个sql查询,为每个UserID返回最后创建的行,其结果将如下所示(在上一行中以开头的行):

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

You can use a CTE (Common Table Expression) with the ROW_NUMBER function: 您可以将CTE(公用表表达式)与ROW_NUMBER函数一起使用:

;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. 此CTE通过UserID对数据进行“分区”,对于每个分区, ROW_NUMBER函数会发出从1开始并由Created DESC排序的序号-因此,最新行将获得RowNum = 1 (对于每个UserID ),这是我选择的从CTE中的SELECT语句之后。

I know this is an old question at this point, but I was having the same problem in MySQL, and I think I have figured out a standard sql way of doing this. 我知道这是一个老问题了,但是我在MySQL中也遇到了同样的问题,我想我已经找到了执行此操作的标准sql方法。 I have only tested this with MySQL, but I don't believe I am using anything MySQL-specific. 我只在MySQL上进行过测试,但是我不相信我在使用任何MySQL特定的东西。

select mainTable.* from YourTable mainTable, (
    select UserID, max(Created) as Created
    from YourTable
    group by UserID
) dateTable 
where mainTable.UserID = dateTable.UserID
and mainTable.Created = dateTable.Created

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM