SQL Server查詢分組結果中第一條記錄的方法

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倒序排序,給查詢好的每一個組中的數據都編上行號it

相關文章
相關標籤/搜索