我试图基本上将一个计数除以SQL中另一个表的数字查询
MOVIECOUNT AS (
SELECT COUNT(MS.MOVID) AS MOVCOUNT, MG.GENRE AS GENREPERCOUNT
FROM MOVIESUCCESS MS
INNER JOIN MOVIES_GENRES MG ON MG.MOVIE_ID = MS.movid
group by MG.GENRE
)
SELECT (MC.MOVCOUNT / COUNT(DG.MOVIE_ID))
FROM MOVIECOUNT MC, DIRECTORS_GENRES DG
WHERE MC.GENREPERCOUNT = DG.GENRE
GROUP BY DG.GENRE
我无法让后一部分进行编译(MOVIECOUNT可以正常工作 - 仅供参考)。架构的其余部分并不重要,我让其余的代码工作。 我基本上只是试图获得我在moviecount中找到的计数(按类型完成)并将其除以相同类型的所有电影的计数。想法? Oracle SQL
答案 0 :(得分:1)
您可能需要在加入之前单独计算每个聚合:
with mgc as (
select
mg.genre,
count(*) as moviecount
from
moviesuccess ms
inner join
movies_genres mg
on mg.movie_id = ms.movid
group by
mg.genre
), dgc as (
select
dg.genre,
count(*) as directorcount
from
directors_genres dg
group by
dg.genre
) select
mgc.genre,
mgc.moviecount / dgc.directorcount
from
mgc
inner join
dgc
on mgc.genre = dgc.genre;
答案 1 :(得分:1)
您可以使用您正在采用的方法执行此操作,您只需要更加小心聚合:
WITH MOVIECOUNT AS (
SELECT COUNT(MS.MOVID) AS MOVCOUNT, MG.GENRE AS GENREPERCOUNT
FROM MOVIESUCCESS MS INNER JOIN
MOVIES_GENRES MG
ON MG.MOVIE_ID = MS.movid
group by MG.GENRE
)
SELECT (MC.MOVCOUNT / COUNT(DG.MOVIE_ID))
FROM MOVIECOUNT MC JOIN
DIRECTORS_GENRES DG
ON MC.GENREPERCOUNT = DG.GENRE
GROUP BY MC.GENRE, MC.MOVCOUNT;