表结构如下:
UserID(用户ID) TM(时间) Item(参数值) 三个字段,类型分别为字符串、日期时间、数值型,其中UserID和TM联合为表的主键,每个用户定时5分钟添加一条记录到该数据表中,如下:
用户1 2013-11-25 00:00:00 100.0
用户2 2013-11-25 00:00:00 100.0
用户1 2013-11-25 00:05:00 100.0
用户2 2013-11-25 00:05:00 100.0
用户3 2013-11-25 00:35:00 100.0
现在求一条SQL语句,要求查出每个用户按时间来的最新的一条记录,谢谢大家。
Group ,Orderby ,Top(1).你结合在一起组织一下
select max(UserID) as UserID,max(TM) as TM,max(Item) as Item from 表名 group by UserID
select UserID, max(TM) as TM
from your_table
group by UserID
你的表设计的不科学.
没有与业务无关的 主键
select * from T1 where ( (cast(UserID as nvarchar)+cast(TM as nvarchar)) = (select (cast(UserID as nvarchar)+cast(TM as nvarchar)) from T1 group by UserID having TM=Max(TM) )
select UserID as UserID,max(TM) as TM,max(Item) as Item from 表名 group by UserID
with t as (select UserID , max(TM) as TM from tbName group by UserID )
select *
from tbName d inner join t on d.UserID =t.UserID and d.TM =t.TM
SELECT *
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY USERID ORDER BY A.TM DESC) LEV,
A.*
FROM TAB A)
WHERE LEV = 1
这个sql也可以