Guest User

Untitled

a guest
Apr 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. CREATE TABLE BlogPosts
  2. (
  3. PostID INT PRIMARY KEY not null,
  4. PostTitle NVARCHAR ,
  5. BlogID int,
  6. TotalComments int
  7. )
  8.  
  9. SELECT TOP 5 *
  10. FROM BlogPosts as t0
  11. WHERE t0.PostID = (SELECT TOP 1 t1.PostID
  12. FROM BlogPosts as t1
  13. WHERE t0.BlogID = t1.BlogID
  14. ORDER BY t1.TotalComments DESC)
  15.  
  16. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 1, 'A', 1, 3
  17. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 2, 'B', 1, 4
  18. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 3, 'C', 2, 5
  19. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 4, 'D', 2, 6
  20. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 5, 'E', 2, 7
  21. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 6, 'F', 1, 8
  22. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 7, 'G', 3, 9
  23. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 8, 'H', 4, 10
  24. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 9, 'I', 5, 11
  25. INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 10, 'J', 6, 5
  26.  
  27. SELECT TOP 5 *
  28. FROM @BlogPosts bp INNER JOIN
  29. (
  30. SELECT BlogID,
  31. MAX(TotalComments) MaxComments
  32. FROM @BlogPosts
  33. GROUP BY BlogID
  34. ) maxCommentsPerBlog ON bp.BlogID = maxCommentsPerBlog.BlogID
  35. AND bp.TotalComments = maxCommentsPerBlog.MaxComments
  36. ORDER BY bp.TotalComments DESC
  37.  
  38. SELECT * FROM (
  39. SELECT *, Ranking = ROW_NUMBER() OVER (PARTITION BY BlogID ORDER BY TotalComments DESC)
  40. FROM BlogPosts
  41. ) a
  42. WHERE Ranking = 1
  43.  
  44. SELECT b.*
  45. FROM (
  46. SELECT DISTINCT BlogID
  47. FROM BlogPosts
  48. ) a
  49. CROSS APPLY (
  50. SELECT TOP 1 b.* FROM BlogPosts b
  51. WHERE a.BlogID = b.BlogID
  52. ORDER BY b.TotalComments DESC
  53. ) b
Add Comment
Please, Sign In to add comment