简体   繁体   English

CTE后按最大列值的Sql分组

[英]Sql group by max column value after CTE

I have this query:我有这个查询:

WITH messages_ranked 
AS ( 
   SELECT p.Date, p.RecipientId, p.RecipientType, p.Id, p.text, p.userId,
   ROW_NUMBER() OVER(PARTITION BY p.RecipientId, p.userId 
   ORDER BY p.Id DESC) 
   AS rk 

   FROM ChatMessages p
   JOIN ChatGroupMemberships as g 
   ON p.recipientId = g.groupId
   WHERE g.userId = XXX <-- user id
) 

SELECT date, recipientId as groupId, recipientType as groupType, id, text, userId, rk
FROM messages_ranked s 
where rk = 1

Order BY s.date DESC 

Which yields me this:这给我带来了这个:

图像1

What I'd need is to reduce result rows of this query so that for every unique groupId only the row with highest value of date would be returned.我需要的是减少此查询的结果行,以便对于每个唯一的groupId仅返回具有最高date值的行。

So for example from the first three rows only the first would be returned, as they share the same groupId and the first row has the newest date.因此,例如从前三行只返回第一行,因为它们共享相同的groupId并且第一行具有最新日期。

I tried to follow example here How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?我试图在这里遵循示例如何通过 SQL 中的另一列选择具有 MAX(Column value), DISTINCT 的行? as my question is closely related but I can't seem to do it right.因为我的问题密切相关,但我似乎做对了。

I am guessing that this does what you want:我猜这可以满足您的需求:

WITH messages_ranked AS ( 
      SELECT p.Date, p.RecipientId, p.RecipientType, p.Id, p.text, p.userId,
             ROW_NUMBER() OVER (PARTITION BY p.RecipientId ORDER BY p.dATE DESC) AS seqnum
      FROM ChatMessages p JOIN
           ChatGroupMemberships as g 
           ON p.recipientId = g.groupId
      WHERE g.userId = XXX <-- user id
     ) 
SELECT date, recipientId as groupId, recipientType as groupType, id, text, 
       userId, seqnum
FROM messages_ranked s 
WHERE seqnum = 1
ORDER BY s.date DESC ;

I don't think you need to use row_number() twice.我认为您不需要使用row_number()两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM