Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Problem 5. Answers with their Question with their Category and User
- 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.
- Steps:
- 1. Select all columns from Answers table.
- 2. Join Questions table by QuestionId foreign key.
- 3. Join Categories table by CategoryId foreign key.
- 4. Join Users table by UserId foreign key in Answers table.
- 5. Add order by statement by Category Name, Answer Author and CreatedOn.
- 6. Select only the required columns with their aliases.
- */
- SELECT
- A.Content AS [Answer Content],
- A.CreatedOn AS [CreatedOn],
- U.Username AS [Answer Author],
- Q.Title AS [Question Title],
- C.Name AS [Category Name]
- FROM dbo.Answers A
- INNER JOIN dbo.Users U
- ON U.ID = A.UserID
- INNER JOIN dbo.Questions Q
- ON Q.ID = A.QuestionID
- INNER JOIN dbo.Categories C
- ON C.ID = Q.CategoryID
- ORDER BY
- C.NAME ASC,
- U.Username ASC,
- A.CreatedOn ASC
- SELECT
- CAST(a.Content AS NVARCHAR(MAX)) AS [Answer Content],
- A.CreatedOn AS [CreatedOn],
- U.Username AS [Answer Author],
- Q.Title AS [Question Title],
- C.Name AS [Category Name]
- FROM dbo.Answers A
- INNER JOIN dbo.Users U
- ON U.ID = A.UserID
- INNER JOIN dbo.Questions Q
- ON Q.ID = A.QuestionID
- INNER JOIN dbo.Categories C
- ON C.ID = Q.CategoryID
- GROUP BY CAST(A.Content AS NVARCHAR(MAX)), A.CreatedOn, U.Username, Q.Title, C.Name
- ORDER BY
- C.NAME ASC,
- U.Username ASC,
- A.CreatedOn ASC
- --Author solution, does not work:
- SELECT a.Content AS [Answer Content], a.CreatedOn, u.Username AS [Answer Author], q.Title AS [Question Title], c.Name AS [Category Name]
- FROM Answers a
- JOIN Questions q ON q.Id = a.QuestionId
- JOIN Categories c ON q.CategoryId = c.Id
- JOIN Users u ON a.UserId = u.Id
- ORDER BY c.Name -- TODO: Fix order by! The result is not unique!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement