1

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:

img1

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.

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.

I tried to follow example here How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL? as my question is closely related but I can't seem to do it right.

Matěj Štágl
  • 870
  • 1
  • 9
  • 27
  • Which RDBMS is this for? Please add a tag to specify whether you're using `mysql`, `postgresql`, `sql-server`, `oracle` or `db2` - or something else entirely. – marc_s Jan 28 '20 at 20:15

1 Answers1

2

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks! That works like a charm and you really simplified it. This was a follow up for my previous question where I worked my way here. Accepting in 10 minutes. https://stackoverflow.com/questions/59955002/sql-cte-scope-in-query – Matěj Štágl Jan 28 '20 at 20:02