考虑下表的数据
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
我想创建一个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
答案 0 :(得分:1)
您可以将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
此CTE按UserID
“分区”您的数据,对于每个分区,ROW_NUMBER
函数会发出序号,从1开始并按Created DESC
排序 - 所以最新一行得到RowNum = 1
(对于每个UserID
),这是我在后面的SELECT语句中从CTE中选择的。
答案 1 :(得分:0)
我知道这是一个老问题,但我在MySQL中遇到了同样的问题,我想我已经找到了一种标准的sql方式来做到这一点。我只用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