Advertisement
Guest User

fulloutjoin

a guest
Oct 10th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. [SQL Fiddle][1]
  2.  
  3. **MS SQL Server 2008 Schema Setup**:
  4.  
  5. CREATE TABLE tblMessages
  6. (
  7. mbrId int primary key,
  8. messageCount int
  9. );
  10.  
  11. CREATE TABLE tblNotifications
  12. (
  13. mbrId int primary key,
  14. notificationCount int
  15. );
  16.  
  17. CREATE TABLE tblRequests
  18. (
  19. mbrId int primary key,
  20. requestCount int
  21. );
  22.  
  23. INSERT INTO tblMessages
  24. (mbrId, messageCount)
  25. VALUES
  26. (2, 20),
  27. (3, 2);
  28.  
  29. INSERT INTO tblNotifications
  30. (mbrId, notificationCount)
  31. VALUES
  32. (1, 1),
  33. (3, 2);
  34.  
  35. INSERT INTO tblRequests
  36. (mbrId, requestCount)
  37. VALUES
  38. (3, 2);
  39.  
  40. **Query 1**:
  41.  
  42. SELECT COALESCE(m.mbrid, r.mbrid, n.mbrid) AS mbrid, ISNULL(m.messageCount,0) AS messageCount, ISNULL(n.NotificationCount,0) AS NotificationCount, ISNULL(r.requestCount, 0) AS requestCount
  43. FROM tblMessages m
  44. full JOIN tblNotifications n
  45. ON m.mbrid = n.mbrid
  46. AND m.messageCount > 0
  47. AND n.notificationCount > 0
  48. full JOIN tblRequests r
  49. ON m.mbrid = r.mbrid
  50. AND r.requestCount > 0
  51. ORDER BY mbrid
  52.  
  53.  
  54. **[Results][2]**:
  55.  
  56. | MBRID | MESSAGECOUNT | NOTIFICATIONCOUNT | REQUESTCOUNT |
  57. |-------|--------------|-------------------|--------------|
  58. | 1 | 0 | 1 | 0 |
  59. | 2 | 20 | 0 | 0 |
  60. | 3 | 2 | 2 | 2 |
  61.  
  62.  
  63.  
  64. [1]: http://sqlfiddle.com/#!3/751f8/18
  65.  
  66. [2]: http://sqlfiddle.com/#!3/751f8/18/0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement