我有这张桌子:
Movies (ID, Genre)
电影可以有多种类型,因此ID不是特定于某种类型,它是多对多的关系。我想要一个查询来查找恰好有4种类型的电影总数。我当前的查询是
SELECT COUNT(*)
FROM Movies
GROUP BY ID
HAVING COUNT(Genre) = 4
但是,这会返回一个4的列表而不是总和。如何获得总和而不是count(*)
的列表?
答案 0 :(得分:72)
一种方法是使用嵌套查询:
SELECT count(*)
FROM (
SELECT COUNT(Genre) AS count
FROM movies
GROUP BY ID
HAVING (count = 4)
) AS x
内部查询获取所有具有4种类型的电影,然后外部查询计算内部查询返回的行数。
答案 1 :(得分:6)
SELECT COUNT(*)
FROM (SELECT COUNT(*)
FROM movies
GROUP BY id
HAVING COUNT(genre) = 4) t
答案 2 :(得分:2)
也许
SELECT count(*) FROM (
SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total
虽然这不是所有电影的总和,但有多少有4种类型。
所以也许你想要
SELECT sum(
SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total
答案 3 :(得分:1)
怎么样:
SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a