Advertisement
Guest User

Answers with their Question with their Category and User

a guest
Jul 8th, 2015
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.98 KB | None | 0 0
  1. /*
  2. Problem 5.  Answers with their Question with their Category and User
  3. Find all answers along with their questions, along with question category, along with question author sorted by Category Name, then by Answer Author, then by CreatedOn. Display the answer content, created on, question title, category name and author username. Name the columns exactly like in the table below.
  4. Steps:
  5. 1.  Select all columns from Answers table.
  6. 2.  Join Questions table by QuestionId foreign key.
  7. 3.  Join Categories table by CategoryId foreign key.
  8. 4.  Join Users table by UserId foreign key in Answers table.
  9. 5.  Add order by statement by Category Name, Answer Author and CreatedOn.
  10. 6.  Select only the required columns with their aliases.
  11. */
  12.  
  13. SELECT
  14.     A.Content AS [Answer Content],
  15.     A.CreatedOn AS [CreatedOn],
  16.     U.Username AS [Answer Author],
  17.     Q.Title AS [Question Title],
  18.     C.Name AS [Category Name]
  19. FROM dbo.Answers A
  20. INNER JOIN dbo.Users U
  21. ON U.ID = A.UserID
  22. INNER JOIN dbo.Questions Q
  23. ON Q.ID = A.QuestionID
  24. INNER JOIN dbo.Categories C
  25. ON C.ID = Q.CategoryID
  26. ORDER BY
  27.     C.NAME ASC,
  28.     U.Username ASC,
  29.     A.CreatedOn ASC
  30.  
  31. SELECT
  32.     CAST(a.Content AS NVARCHAR(MAX)) AS [Answer Content],
  33.     A.CreatedOn AS [CreatedOn],
  34.     U.Username AS [Answer Author],
  35.     Q.Title AS [Question Title],
  36.     C.Name AS [Category Name]
  37. FROM dbo.Answers A
  38. INNER JOIN dbo.Users U
  39. ON U.ID = A.UserID
  40. INNER JOIN dbo.Questions Q
  41. ON Q.ID = A.QuestionID
  42. INNER JOIN dbo.Categories C
  43. ON C.ID = Q.CategoryID
  44. GROUP BY CAST(A.Content AS NVARCHAR(MAX)), A.CreatedOn, U.Username, Q.Title, C.Name
  45. ORDER BY
  46.     C.NAME ASC,
  47.     U.Username ASC,
  48.     A.CreatedOn ASC
  49.  
  50. --Author solution, does not work:
  51.  
  52. SELECT a.Content AS [Answer Content], a.CreatedOn, u.Username AS [Answer Author], q.Title AS [Question Title], c.Name AS [Category Name]
  53. FROM Answers a
  54.   JOIN Questions q ON q.Id = a.QuestionId
  55.   JOIN Categories c ON q.CategoryId = c.Id
  56.   JOIN Users u ON a.UserId = u.Id
  57. ORDER BY c.Name -- TODO: Fix order by! The result is not unique!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement