0

The title may be confusing, here is my schema

enter image description here

and here is the result of my query

enter image description here

how can i remove duplicates and just get the values highlighted, i am trying to order by message time

Regards

Community
  • 1
  • 1
Dakait
  • 2,531
  • 1
  • 25
  • 43

2 Answers2

1

One way in SQL-Server is using a ranking function like ROW_NUMBER:

WITH CTE AS
(
    SELECT c.ContactID, c.Name, m.Text, m.Messagetime,
           RN = ROW_NUMBER() OVER (PARTITION BY c.ContactID
                                   ORDER BY m.MessageTime DESC)
    FROM dbo.Contacts c
    INNER JOIN Messages m ON c.ContactID = m.ContactID
)
SELECT ContadctId, Name, Text, Messagetime
FROM CTE
WHERE RN = 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

The following syntax will work in both SQL Server and MySQL:

SELECT c.ContactID, c.Name, m.Text, m.Messagetime
FROM Contacts c INNER JOIN
     Messages m
     ON c.ContactID = m.ContactID
WHERE NOT EXISTS (select 1
                  from messages m2
                  where m2.ContactId = m.ContactId and
                        m2.MessageTime > m.MessageTime
                 )
ORDER BY m.MessageTime desc;

Note that if you have duplicate most recent message times, then all will be returned.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786