我正在撰写一个查询,以选择喜剧类型电影中最多的总提名。到目前为止我有以下查询
SELECT m.movie_title, m.release_year, COUNT(*)
FROM MOVIE m JOIN NOMINATION n
ON (n.movie_title=m.movie_title AND n.release_year=m.release_year)
WHERE m.genre='Comedy' GROUP BY m.movie_title, m.release_year;
如果我执行以下查询
SELECT m.movie_title, m.release_year
FROM MOVIE m
WHERE (m.genre='Comedy') GROUP BY m.movie_title,m.release_year);
它返回3个结果。我的动机是获得一个具有流派喜剧电影提名最多的结果。
我的逻辑是不正确的?我仍然是sql(oracle11g)的初学者并自学。
我已经在线查看了多个教程,但到目前为止还没有任何帮助。
感谢您的帮助。
答案 0 :(得分:1)
让我们用employee表示例来理解它。
我有三行显示每个部门的计数(*)。
SQL> WITH data AS
2 ( SELECT deptno, COUNT(*) rn FROM emp GROUP BY deptno
3 )
4 SELECT * FROM DATA
5 /
DEPTNO RN
---------- ----------
30 6
20 5
10 3
现在,我想要一行具有最大部门数。
SQL> WITH data AS
2 ( SELECT deptno, COUNT(*) rn FROM emp GROUP BY deptno
3 )
4 SELECT * FROM DATA WHERE rn =
5 (SELECT MAX(rn) FROM data
6 )
7 /
DEPTNO RN
---------- ----------
30 6
SQL>
或者,也可以写成:
SQL> WITH data1 AS
2 ( SELECT deptno, COUNT(*) rn FROM emp GROUP BY deptno
3 ),
4 data2 AS
5 ( SELECT MAX(rn) max_rn FROM DATA1
6 )
7 SELECT d1.* FROM data1 d1, data2 d2 WHERE d1.rn = d2.max_rn
8 /
DEPTNO RN
---------- ----------
30 6
SQL>
因此,在您的情况下,请使用MAX
函数。
其他方法是使用ANALYTIC
函数,ROW_NUMBER
为每个计数(*)指定RANK
,然后选择最高排名。
例如,
SQL> WITH data AS
2 (SELECT deptno,
3 row_number() OVER( ORDER BY COUNT(*) DESC) rn
4 FROM emp
5 GROUP BY deptno
6 )
7 SELECT deptno FROM DATA WHERE rn = 1
8 /
DEPTNO
----------
30
SQL>
答案 1 :(得分:1)
尝试这样的事情:
SELECT n.movie_title, n.release_year, COUNT(*) nominations
FROM NOMINATION n
LEFT JOIN MOVIE m ON n.movie_title=m.movie_title AND n.release_year=m.release_year
WHERE m.genre='Comedy'
GROUP BY n.movie_title,n.release_year
ORDER BY nominations DESC
你的方法是:
为了更好地理解这个过程,请尝试上面的行查询行,并查看两者之间的结果。在执行前两行时,首先查看结果。然后添加第三行并再次执行。等等。
更新(删除LIMIT后):
在
SELECT * FROM (
... above statement here ...
) WHERE ROWNUM=1;
有关详细信息,请参阅How do I limit the number of rows returned by an Oracle query after ordering?。
答案 2 :(得分:1)
select * from (
select
movie_title,
release_year,
row_number() over (order by count(*) desc) rnk
from
movie m join
nomination n using(movie_title, release_year)
where
m.genre = 'Comedy'
group by
movie_title,
release_year
)
where
rnk = 1
答案 3 :(得分:1)
如果您按照提名的数量命令您进行查询并获得"第一个"之一:
select movie_title, release_year, cnt
from (
SELECT m.movie_title, m.release_year, count(n.movie_title) as cnt
FROM MOVIE m
LEFT JOIN NOMINATIONS n
ON n.movie_title=m.movie_title
AND n.release_year=m.release_year
WHERE m.genre='Comedy'
GROUP BY m.movie_title,m.release_year
ORDER BY COUNT(n.movie_title) desc
)
where rownum = 1;
另一种选择是使用窗口函数和count(...) over ( ... )
答案 4 :(得分:0)
最好使用连接
SELECT (select COUNT(*) from NOMINATION As COUNT), m.movie_title, m.release_year,n.movie_title,n.release_year
FROM MOVIE m
Join NOMINATION
On n.movie_title=m.movie_title AND n.release_year=m.release_year
WHERE m.genre='Comedy'
GROUP BY m.movie_title,m.release_year