Advertisement
snovvblind

CS145 - Stanford - SQL Movie-Rating Query Exercises

Nov 1st, 2011
6,194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. DATABASE: http://www.db-class.org/course/resources/index?page=moviedata
  2.  
  3. 1. Find the titles of all movies directed by Steven Spielberg.
  4.  
  5. SELECT Title
  6. FROM Movie
  7. WHERE Director = 'Steven Spielberg'
  8.  
  9. 2. Find all years that have a movie that received a rating of 4 or 5, and sort them in increasing order.
  10.  
  11. SELECT DISTINCT Year
  12. FROM Movie
  13. JOIN Rating ON Rating.mID = Movie.mID
  14. WHERE Stars > '3'
  15. ORDER BY Year
  16.  
  17. 3. Find the titles of all movies that have no ratings.
  18.  
  19. SELECT DISTINCT Title
  20. FROM Movie
  21. JOIN Rating
  22. WHERE Movie.mID NOT IN (select Rating.mID FROM Rating)
  23.  
  24. 4. Some reviewers didn't provide a date with their rating. Find the names of all reviewers who have ratings with a NULL value for the date.
  25.  
  26. SELECT Name
  27. FROM Rating
  28. JOIN Reviewer ON Reviewer.rID = Rating.rID
  29. WHERE RatingDate IS Null
  30.  
  31. 5. Write a query to return the ratings data in a more readable format: reviewer name, movie title, stars, and ratingDate. Also, sort the data, first by reviewer name, then by movie title, and lastly by number of stars.
  32.  
  33. SELECT Name, Title, Stars, RatingDate
  34. FROM Rating, Movie
  35. JOIN Reviewer ON Rating.rID = Reviewer.rID
  36. WHERE Rating.mID = Movie.mID
  37. ORDER BY Name, Title, Stars
  38.  
  39. 6. For all cases where the same reviewer rated the same movie twice and gave it a higher rating the second time, return the reviewer's name and the title of the movie.
  40.  
  41. SELECT Name, Title
  42. FROM Rating
  43. JOIN Reviewer ON Rating.rID = Reviewer.rID
  44. JOIN Movie ON Rating.mID = Movie.mID
  45. JOIN Rating AS r2 ON Rating.mID = r2.mID AND Rating.rID = r2.rID
  46. WHERE r2.ratingDate > Rating.ratingDate AND r2.stars > Rating.stars
  47.  
  48. 7. For each movie that has at least one rating, find the highest number of stars that movie received. Return the movie title and number of stars. Sort by movie title.
  49.  
  50. SELECT Title, Stars
  51. FROM Movie
  52. JOIN Rating ON Rating.mID = Movie.mID
  53. GROUP BY Title
  54. HAVING Count (stars) >= 2
  55.  
  56. 8. For each movie, return the title and the 'rating spread', that is, the difference between highest and lowest ratings given to that movie. Sort by rating spread from highest to lowest, then by movie title.
  57.  
  58. SELECT Title, Spread
  59. FROM Movie
  60. JOIN (SELECT mID, MAX(stars) - MIN(stars) AS Spread
  61. FROM Rating GROUP BY mID) Rating
  62. ON Movie.mID = Rating.mID
  63. ORDER BY Spread DESC, Title
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement