我有一个表,用日期时间保存特定用户的多个记录,我的要求是我只需要通过查询获得最新记录。我不知道如何获取此类数据。
表格
Create Table tblReport(
USERID LONG, ReportDateTime Datetime
)
当前记录
USERID ReportDateTime
1 2017-04-18 21:41:33.903
4 2017-04-20 01:16:00.653
4 2017-04-26 20:00:20.497
71 2017-04-17 22:31:37.437
4 2017-04-26 20:01:20.933
225 2017-04-20 00:58:10.253
225 2017-04-25 23:09:34.433
1 2017-04-18 23:35:00.567
所需输出
USERID ReportDateTime
1 2017-04-18 23:35:00.567
4 2017-04-26 20:01:20.933
71 2017-04-17 22:31:37.437
225 2017-04-25 23:09:34.433
我的查询
select USERID,max(ReportDateTime) from tblReport group by USERID, ReportDateTime order by USERID
答案 0 :(得分:2)
从ReportDateTime
删除group by
。
select
UserId
, ReportDateTime = max(ReportDateTime)
from tblReport
group by userid
order by userid
rextester演示:http://rextester.com/CLQ69624
返回:
+--------+-------------------------+
| UserId | ReportDateTime |
+--------+-------------------------+
| 1 | 2017-04-18 23:35:00.567 |
| 4 | 2017-04-26 20:01:20.933 |
| 71 | 2017-04-17 22:31:37.437 |
| 225 | 2017-04-25 23:09:34.433 |
+--------+-------------------------+
答案 1 :(得分:1)
另一种选择是使用With Ties子句
Select Top 1 With Ties *
From tblReport
Order By Row_Number() over (Partition By UserID Order by ReportDateTime Desc)