Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 13th, 2012  |  syntax: None  |  size: 1.00 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Query for exact match of users in a conversation in SQL Server
  2. CONVERSATION
  3. Id, Subject, Type
  4.  
  5. USERCONVERSATION
  6. Id, UserId, ConversationId
  7.        
  8. SELECT ConversationID
  9. FROM UserConversation
  10. GROUP BY ConversationID
  11. HAVING
  12.    Count(UserID) = 3 -- this isn't necessary but might improve performance
  13.    AND Sum(CASE WHEN UserID IN (1, 2, 3) THEN 1 ELSE 0 END) = 3
  14.        
  15. SELECT ConversationID
  16. FROM
  17.    UserConversation UC
  18.    LEFT JOIN (
  19.       SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
  20.    ) U (UserID) ON UC.UserID = U.UserID
  21. GROUP BY ConversationID
  22. HAVING
  23.    Count(U.UserID) = 3
  24.    AND Count(UC.UserID) = 3
  25.        
  26. SELECT
  27.    Coalesce(C.ConversationID, UC.ConversationID) ConversationID
  28.    -- Or could be Min(C.ConversationID)
  29. FROM
  30.    Conversation C
  31.    CROSS JOIN (
  32.       SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
  33.    ) U (UserID)
  34.    FULL JOIN UserConversation UC
  35.       ON C.ConversationID = UC.ConversationID
  36.       AND U.UserID = UC.UserID
  37. GROUP BY Coalesce(C.ConversationID, UC.ConversationID)
  38. HAVING Count(*) = Count(U.UserID)