日期:2014-05-16  浏览次数:20433 次

类似微信的”正在聊天“列表那样,查询数据库最新的好友聊天,求大牛
比如 用户A , 与好友B ,C  , 

user1 , friend2 , content , time
A                  B                  1             1
A                  B                  2            1
A                  C                 3             1
A                  B                  4             1
A                  B                  5             1
A                  C                  4             1
A                  B                  5             1
A                  C                  7             1


我要获取最新的  就是  A   C  7  1  和  A  B 5  1  ,请问数据库该如何查询。  有点脑胀,最近。想不出

------解决方案--------------------

if object_id('tempdb..#a') is not null  drop table #a
create table #a 
( user1  varchar(5) , friend2 varchar(5), content varchar, [time] int)
insert into #a 
select 'A','B',1,1  union all
select 'A','B',2,1  union all
select 'A','C',3,1  union all
select 'A','B',4,1  union all
select 'A','B',5,1  union all
select 'A','C',4,1  union all
select 'A','B',5,1  union all
select 'A','C',7,1
---开始查询
select user1 , friend2 ,  content,  time from (
select * ,row_number() over ( partition by user1,friend2 order by m desc ) as num
from (select *,row_number() over (  order by getdate()