Message表中有字段 ID FromID ToID
比如现在有数据是
ID FromID ToID
1 103 102
2 102 103
3 103 102
4 104 102
5 105 102
from代表发送方,to代表接收方
怎么样能按发送方和接收方捆绑分组呢,比如参与者是103和102的时候,不管103发给102,还是102发给103都算是这一组的,然后取出每组最近的,如模拟数据中的话,取出的应该是
ID FromID ToID
1 103 102
4 104 102
5 105 102
求教大家,我想到的都是比较繁琐的方式,用游标什么的。感激不尽。
------解决方案--------------------
create table Message(ID int,FromID int,ToID int)
insert into message select 1,103,102
insert into message select 2,102,103
insert into message select 3,103,102
insert into message select 4,104,102
insert into message select 5,105,102
go
select * from message a
where not exists(select 1 from message where id<a.id and fromid in(a.fromid,a.toid) and toid in(a.fromid,a.toid))
/*
ID FromID ToID
----------- ----------- -----------
1 103 102
4 104 102
5 105 102
(3 行受影响)
*/
go
drop table message
------解决方案--------------------
declare @message table(id int,fromid int,toid int)
insert into @message
select 1 , 103 , 102 union all
select 2 , 102 , 103 union all
select 3 , 103 , 102 union all
select 4 , 104 , 102 union all