我们可以在Sql Server 2017的两列上应用分组依据吗?

时间:2019-02-27 15:55:06

标签: sql sql-server

如何获取与UserID进行过聊天的所有用户的最新消息。我想在两个字段上应用分组依据。数据库就像:

MessageID    Message    MessageCreatorUserID     MessageRecieverUserID   CreatedAt

  1           HI                  4                         1              
  2           Hello               1                         3             
  3           Bye                 1                         3                       
  4           Thanks              1                         2
  5           hii                 1                         3

这是桌子,我的问题是:

用户ID存储在MessageCreatorUserID或MessageRecieverUserID

我想获取所有使用UserID 1进行聊天的用户的最新消息。

3 个答案:

答案 0 :(得分:0)

我认为您正在混淆group by和where子句。

获取所有UserId = 1的消息都位于MessageCreatorUserId或MessageReceiverUserId中:

SELECT * FROM table1 WHERE MessageCreatorUserId = 1 OR MessageReceiverUserId  = 1

现在,我们需要每次对话中的lastMessage:

 SELECT MAX(MessageID), MessageCreatorUserId 
 FROM table1 
 WHERE MessageCreatorUserId = 1 OR MessageReceiverUserId  = 1
 GROUP BY MessageCreatorUserId 

答案 1 :(得分:0)

这是条件分组和您需要的主表之间的联接:

select g.otheruser, t.message from (
  SELECT  
    case 
      when MessageCreatorUserId = 1 then MessageRecieverUserID
      else MessageCreatorUserId
    end otheruser,
    MAX(MessageID) maxid
  FROM tablename 
  WHERE MessageCreatorUserId = 1 OR MessageRecieverUserID  = 1
  GROUP BY 
    case 
      when MessageCreatorUserId = 1 then MessageRecieverUserID
      else MessageCreatorUserId
    end 
) g inner join tablename t
on t.messageid = g.maxid
order by otheruser

请参见demo

答案 2 :(得分:0)

好吧,您可以使用窗口功能:

select t.*
from (select t.*,
             row_number() over (partition by (case when MessageCreatorUserId = 1 then MessageReceiverUserId else MessageCreatorUserId end)
                                order by messageId desc
                               ) as seqnum
      from t
      where 1 in (MessageCreatorUserId, MessageReceiverUserId)
     ) t
where seqnum = 1;