如何从显示中排除几行? " DISTINCT" - SQL SERVER

时间:2017-12-26 16:17:59

标签: sql sql-server

所以我试图只选择来自某个人的最后一条消息。这是我提出的查询

SELECT DISTINCT ISNULL(MessageID, -1) AS "MessageID", ContactID, Msgs.DateS
FROM Contacts LEFT JOIN Msgs ON Contacts.ContactID IN (Msgs.SenderID, Msgs.RecieverID)
WHERE AccountID = 1 ORDER BY Msgs.DateS ASC;

但它仍然向我显示其他消息,我只想要一个出现。这是结果表:

Picture showing the resulting table

6 个答案:

答案 0 :(得分:0)

SELECT DISTINCT ISNULL(m.MessageID, -1) AS "MessageID", ContactID, m.DateS
FROM Contacts c
    OUTER APPLY (
        SELECT TOP 1  Msgs.MessageID, Msgs.DateS 
        FROM Msgs 
        WHERE c.ContactID IN (SenderID, RecieverID)
        ORDER BY DateS DESC
    ) m
WHERE AccountID = 1;

答案 1 :(得分:0)

对于SQL Server 2005或更高版本

{{1}}

答案 2 :(得分:0)

只是一个想法,试试这个:

SELECT ISNULL(MessageID, -1) AS "MessageID", ContactID, max(m.DateS)
FROM Contacts c
LEFT JOIN Msgs m ON c.ContactID IN (m.SenderID, m.RecieverID)
WHERE AccountID = 1 Group By MessageID,c.ContactID 
ORDER BY m.DateS ASC;

答案 3 :(得分:0)

而不是DISTINCT,您需要aggregate function

SELECT ISNULL(MessageID, -1) AS "MessageID", ContactID, MAX(Msgs.DateS)
FROM Contacts 
LEFT JOIN Msgs ON Contacts.ContactID IN (Msgs.SenderID, Msgs.RecieverID) 
WHERE AccountID = 1 
GROUP BY MessageID, ContactID
ORDER BY Msgs.DateS ASC;

答案 4 :(得分:0)

如果您只想要“最后”消息,请使用top 1

SELECT TOP 1 COALESCE(m.MessageID, -1) AS "MessageID", c.ContactID, m.DateS
FROM Contacts c LEFT JOIN
     Msgs m
     ON c.ContactID IN (m.SenderID, m.RecieverID)
WHERE AccountID = 1
ORDER BY Msgs.DateS DESC;

答案 5 :(得分:0)

SELECT * FROM (
        SELECT  ISNULL(MessageID, -1) AS "MessageID", ContactID, Msgs.DateS,ROW_NUMBER()OVER(PARTITION BY AccountID ORDER BY Msgs.DateS DESC ) AS Seq
        FROM Contacts 
        LEFT JOIN Msgs ON Contacts.ContactID IN (Msgs.SenderID, Msgs.RecieverID)
) AS t WHERE t.seq=1 AND AccountID = 1 
ORDER BY Msgs.DateS ASC;