您的位置:首页 > 数据库

SQL Server查询分组结果中第一条记录的方法

2016-03-02 15:24 309 查看
select * from
(
select mp.MsgID,m.Content,m.CreatorID,m.CreateTime,ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc) as new_index
from U_Account_WX_MsgProperty mp
join U_Account_WX_Messages m on mp.MsgID=m.MsgID
where mp.UserID=453 and mp.IsRead=0 and mp.IsDelete=0
and m.CreateTime between '2016-01-01' and '2016-03-30'
) result
where result.new_index=1

注意partition后面跟着的是分组字段,也就是根据CreatorID分组
ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc)这行语句的意思是根据CreatorID分组并且按照CreateTime倒序排序,给查询好的每个组中的数据都编上行号
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: