Reputation: 4049
I am currently completing the More JOIN operations tutorial of sqlzoo and encountered the following code as the answer to #12:
SELECT yr,COUNT(title)
FROM movie
JOIN casting
JOIN actor
ON actorid=actor.id AND movie.id=movieid
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)=
(SELECT MAX(c) FROM
(SELECT yr, COUNT(title) AS c
FROM movie
JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr) AS t
)
Is there not a more concise way to express this code?
Upvotes: 1
Views: 256
Reputation: 1010
It looks like the original site's suggested answer does not match the question they were asking.
Best answer to what they asked:
SELECT yr,COUNT(title) FROM
movie JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)>2
Their answer was:
SELECT yr,COUNT(title) FROM
movie JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)=
(SELECT MAX(c) FROM (SELECT yr,COUNT(title) AS c
FROM movie
JOIN casting ON movie.id=movieid JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr) AS t
)
But this actually answers a different question, which is: "For the year in which he made the most movies, what year was that and how many movies did he make?"
Upvotes: 1
Reputation: 9149
Yes. If I understand the quesiton correctly it is much more simple.
SELECT yr,COUNT(title)
FROM movie JOIN casting ON movie.id=movieid
JOIN
actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title) > 2
Upvotes: 2