我有一个包含以下表格的数据库:
ACTOR (id, fname, lname, gender)
MOVIE (id, name, year, rank)
DIRECTOR (id, fname, lname)
CAST (a_id, m_id, role)
MOVIE_DIRECTOR (d_id, m_id)
现在我要检索以下问题的数据。
是:“十年是连续10年的序列。例如,1965、1966,...,1974是十年,1967、1968,...,1976也是如此。电影数量最多的十年”
答案 0 :(得分:2)
我可以通过生成年份,加入电影,然后进行汇总来做到这一点:
select y.year as decade_start, y.year + 9 as decade_end,
count(*) as num_movies
from (select distinct year from movies) y join
movies m
on m.year >= y.year and m.year < y.year + 10
group by y.year
order by count(*) desc
limit 1;
答案 1 :(得分:1)
您尝试过这样的事情吗?
select
m.year as decade_begin,
count(rollup.id) as movies_count
from
MOVIE m,
MOVIE rollup
where
rollup.year >= decade_begin and rollup.year < decade_begin+10
group by
decade_begin
order by
movies_count;
答案 2 :(得分:1)
在这里,只有MOVIE表才很重要。
在MySql 8.x中,可以为此使用CTE上的自联接。
WITH MOV AS
(
SELECT year as movie_year, COUNT(id) as total_movies
FROM MOVIE
GROUP BY year
)
SELECT
m1.movie_year as decade_start,
MAX(m2.movie_year) as decade_end,
SUM(m2.total_movies) as total_movies
FROM MOV m1
LEFT JOIN MOV m2 ON (m2.movie_year BETWEEN m1.movie_year AND m1.movie_year + 9)
GROUP BY m1.movie_year
ORDER BY SUM(m2.total_movies) DESC
LIMIT 1
在不支持CTE的MySql 5.x中,只需用来自CTE的查询的子查询替换m1和m2的MOV。