这是我在sql server 2008中的表结构:
+--------+-----+---------------------+
| user | val | time |
+--------+-----+---------------------+
| kk | 21 | 2011-12-12 12:23:00 |
| dd | 33 | 2011-12-12 12:23:00 |
| kk | 22 | 2011-12-12 12:23:30 |
| dd | 33 | 2011-12-12 12:23:30 |
+--------+-----+---------------------+
表中的此记录每30秒由其他应用程序更新。
现在,我想查询表中所有用户的最新记录。
使用一个SQL查询实现它的任何方法吗?
答案 0 :(得分:2)
这将列出用户和最新时间条目
select user,max(time)
from table
group by user
如果您需要相关数据,请尝试此
select a.*
from table a
join ( select user,max(time) as TheLatest
from table
group by user ) xx
on a.time=xx.theLatest and xx.user=a.user
答案 1 :(得分:0)
SELECT * FROM
(
SELECT
USER
,Val
,ROW_NUMBER() OVER (PARTITION BY User,Time ORDER BY Time DESC) AS SlNo
FROM myTable
) result
WHERE SlNo = 1
答案 2 :(得分:0)
尝试这个
DECLARE @tbl table(ID INT,dtm datetime)
insert into @tbl
values (1,'2011-09-14 00:59:00'),
(2,'2011-09-15'),
(2,'2011-09-15 05:10:00'),
(5,'2011-09-16 05:10:00'),
(8,'2011-10-29 05:10:00'),
(5,'2011-10-29'),
(6,'2011-10-30')
select MAX(dtm),ID from @tbl
GROUP BY ID