Here's my code:
select yr,count(*) from movie join casting on casting.movieid=movie.id join actor on casting.actorid = actor.id where actor.name = 'John Travolta' group by yr;
Here's the question:
Which were the busiest years for 'John Travolta'. Show the number of movies he made for each year.
Here's the table structure:
movie(id, title, yr, score, votes, director) actor(id, name) casting(movieid, actorid, ord)
This is the output I am getting:
yr count(*) 1976 1 1977 1 1978 1 1981 1 1994 1 -- etc.
I need to get the rows for which count(*)
is max. How do I do this?
Try using this SQL SELECT statement: SELECT * FROM employees WHERE department_id=30 AND salary = (SELECT MAX(salary) FROM employees WHERE department_id=30); This will return the employee information for only the employee in department 30 that has the highest salary.
No, we can't use a MAX(COUNT(*) and we can not layer aggregate functions on top of one another in the same SELECT clause. In a subquery, the inner aggregate would have to be performed.
Remarks. COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.
1) COUNT(*)When * is used as an argument, it simply counts the total number of rows including the NULLs. In the example, we will get 11 as count as we have 11 rows in table.
Use:
SELECT m.yr, COUNT(*) AS num_movies FROM MOVIE m JOIN CASTING c ON c.movieid = m.id JOIN ACTOR a ON a.id = c.actorid AND a.name = 'John Travolta' GROUP BY m.yr ORDER BY num_movies DESC, m.yr DESC
Ordering by num_movies DESC
will put the highest values at the top of the resultset. If numerous years have the same count, the m.yr
will place the most recent year at the top... until the next num_movies
value changes.
No, you can not layer aggregate functions on top of one another in the same SELECT clause. The inner aggregate would have to be performed in a subquery. IE:
SELECT MAX(y.num) FROM (SELECT COUNT(*) AS num FROM TABLE x) y
Just order by count(*) desc
and you'll get the highest (if you combine it with limit 1
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With