SQL从一个表中选择多个不同的记录

时间:2012-09-11 11:07:07

标签: sql sql-server tsql sql-server-2008-r2 greatest-n-per-group

我有一张表格如下

ID  |FromId |ToId   |Message|DateTime
------------------------------------------
1   |1      |2      |a      |15:00
2   |1      |2      |b      |15:01
3   |1      |2      |c      |15:02
4   |2      |1      |d      |15:03
5   |3      |1      |e      |15:04
6   |3      |1      |f      |15:05
7   |1      |3      |g      |15:06

我想要得到的是Peers的最后一条消息。

例如:用户1和用户2有4条消息(ID:1,2,3,4),用户1和用户3有3条消息(ID:5,6,7)

我想从用户那里得到最新的Message记录,我需要一个SQL查询,它会得到如下结果:

*sql code here ? -- I need this.

结果(对于:UserID = 1):

ID  |FromId |ToId   |Message|DateTime
------------------------------------------
4   |2      |1      |d      |15:03
7   |1      |3      |g      |15:06

任何想法?我尝试过Distinct等,但它没有以某种方式工作。请帮忙。

对不起伙计我想我忘了提到我需要Peer的最新记录,而不是一个用户的最新记录,例如用户1和用户2我需要他们的最新记录,没有其他记录一个是From或哪个是To ..我需要两个最新记录,在我们的情况下是ID 4,没有其他记录。

6 个答案:

答案 0 :(得分:6)

如果是Sql Server 2005+,您可以使用row_number() over ( ... )对记录进行分组,排序和编号,然后仅检索其组中第一个记录的记录:

; with cte as
(
  select *,
      -- Group by user not being searched for
         row_number() over (partition by case when FromID = @UserID
                                              then ToID
                                              else FromID
                                          end
      -- Last date will be numbered as 1
                            order by [DateTime] desc
                           ) rn
    from Table1
-- Filter only messages sent from or received by certain user
   where (FromID = @UserID or ToID = @UserID)
)
select *
  from cte
-- Get last dates only
 where rn = 1

答案 1 :(得分:2)

使用此Sql:

Declare @tempTeable Table
(
 Id int,
 FromID int,
 ToId int,
 SMessage nvarchar(250),
 SDateTime Time 
)

Insert into @tempTeable values(1,1,2,'a','15:00')
Insert into @tempTeable values(2,1,2,'b','15:01')
Insert into @tempTeable values(3,1,2,'c','15:02')
Insert into @tempTeable values(4,2,1,'d','15:03')
Insert into @tempTeable values(5,3,1,'e','15:04')
Insert into @tempTeable values(6,3,1,'f','15:05')
Insert into @tempTeable values(7,1,3,'g','15:06')

select distinct t1.* from @tempTeable as t1
inner join 
  (select UserID,MAX(SDateTime)as SDateTime from
    (
      select FromId as UserId ,MAX(SDateTime)as SDateTime from  @tempTeable group by 
       FromId
       UNION
       select ToId as UserId,MAX(SDateTime)as SDateTime from  @tempTeable group by   
        ToId) as tbl
        group by UserId) as tblres 
  on (t1.FromID =tblres.UserId  or t1.toId =tblres.UserId) 
  and t1.SDateTime=tblres.SDateTime 

答案 2 :(得分:0)

您需要执行自引用连接,因此内部查询选择每组最大值,外部查询选择匹配的每一行的所有数据。

select * 
from thetable t1 
join(select max(ID) as id,
            FromID 
     from thetable
     group by FromID)t2 on (t1.id=t2.id);

答案 3 :(得分:0)

create table Msgs (ID int primary key, FromId int, ToId int, Message nvarchar(MAX), DateTime time);
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (1   ,1      ,2      ,'a'      ,'15:00');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (2   ,1      ,2      ,'b'      ,'15:01');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (3   ,1      ,2      ,'c'      ,'15:02');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (4   ,2      ,1      ,'d'      ,'15:03');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (5   ,3      ,1      ,'e'      ,'15:04');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (6   ,3      ,1      ,'f'      ,'15:05');
insert into Msgs (ID, FromId, ToId, Message, Datetime) values (7   ,1      ,3      ,'g'      ,'15:06');
select * from Msgs;

with M(ID, FromId, ToId, Message, DateTime, RN) as (
select ID, FromId, ToId, Message, DateTime,
    ROW_NUMBER() over (partition by 
        CASE WHEN FromId < ToID THEN FromId ELSE ToID END, 
        CASE WHEN FromId > ToID THEN FromId ELSE ToID END 
        order by DateTime desc)
from Msgs)
select ID, FromId, ToId, Message, DateTime from M where RN = 1;

drop table Msgs;

返回

ID  FromId  ToId    Message DateTime
1   1   2   a   15:00:00.0000000
2   1   2   b   15:01:00.0000000
3   1   2   c   15:02:00.0000000
4   2   1   d   15:03:00.0000000
5   3   1   e   15:04:00.0000000
6   3   1   f   15:05:00.0000000
7   1   3   g   15:06:00.0000000

ID  FromId  ToId    Message DateTime
4   2   1   d   15:03:00.0000000
7   1   3   g   15:06:00.0000000

答案 4 :(得分:0)

试试这个:

;WITH CTE As(
select id,fromID,ToID,Message,DateTime,0 as sel from Msgs where id=1
union all
select m.id,m.fromID,m.ToID,m.Message,m.DateTime,
CASE WHEN (m.FromId =c.FromId or m.FromId =c.ToId) then 0 else 1 end as sel 
from CTE c inner join Msgs m 
--on (c.FromId = m.FromId and c.ToId = m.ToId) or (c.FromId = m.ToId and c.ToId = m.FromId)
on m.id=c.Id+1
)

select * from CTE where ID in (select ID-1 from CTE where sel=1)
union
select * from CTE where ID = (select max(id) from CTE)

答案 5 :(得分:-1)

create function getlastmessage(
@userid int
)
returns nvarchar(max)
as
select top(1), message from messages 
 where userid=@userid order by messageid desc

在人员表中

select *, getlastmessage(actorid) as lastmessage from people

More info about function syntax


如果您不想使用功能

select 
*, 
(select top(1), message from messages 
  where messages.userid=people.userid order by messageid desc) as lastmessage 
 from people

它会有点乱。