sql >> Databasteknik >  >> RDS >> Mysql

Få sista raden PER grupp

SELECT M.ConversationID, 
MAX(CASE WHEN M.DateTime = X.FirstRow THEN M.Subject END) AS Subject,
CAST(COALESCE(MAX(CASE WHEN M.DateTime = X.LastRowSentByOtherUser 
                       THEN M.DateTime END),X.LastRow) AS DateTime)AS LastTime,
MAX(CASE WHEN M.DateTime = X.LastRow THEN M.Message END) AS Message,
MAX(CASE WHEN FromID = 1 THEN ToID ELSE FromID END) AS OtherParticipantId
FROM messages M
JOIN (
    SELECT ConversationID, MIN(DateTime) AS FirstRow, MAX(DateTime) AS LastRow,
    MAX(CASE WHEN FromID<>1 THEN DateTime END) AS LastRowSentByOtherUser
    FROM messages
    WHERE FromID=1 OR ToID=1
    GROUP BY ConversationID
) X ON X.ConversationID = M.ConversationID
AND (M.DateTime IN (X.FirstRow, X.LastRow, X.LastRowSentByOtherUser))
GROUP BY M.ConversationID
HAVING MAX(CASE WHEN M.DateTime = X.LastRowSentByOtherUser 
                   THEN M.DateTime END) IS NOT NULL


  1. php mysql infoga (max(id)+1)

  2. Postgresql-adapter (sid):kunde inte ansluta till servern

  3. jämför värde med alla fält i en tabell i mysql

  4. Konvertera en befintlig MyISAM-databas till InnoDB med Django