PostgresSQL'WHERE'应该在哪里聚合?

时间:2018-11-02 12:47:31

标签: sql postgresql group-by

以下postgres查询有效:

dvdrental=# SELECT title, COUNT(title) AS c FROM film          
JOIN inventory
ON film.film_id = inventory.film_id GROUP BY film.title LIMIT 5;

      title       | c 
------------------+---
 Academy Dinosaur | 8
 Ace Goldfinger   | 3
 Adaptation Holes | 4
 Affair Prejudice | 7
 African Egg      | 3
(5 rows)

Time: 1.671 ms

然后,如果我想限制发言,以免库存中具有特定数量的电影或计算库存中具有特定数量的电影的数量,这是一个起点:

dvdrental=# SELECT title, COUNT(title) AS c FROM film
JOIN inventory
ON film.film_id = inventory.film_id GROUP BY film.title WHERE c = 4;
ERROR:  syntax error at or near "WHERE"
LINE 3: ...m.film_id = inventory.film_id GROUP BY film.title WHERE c = ...
                                                             ^
Time: 0.337 ms

..但是不起作用。

我在这里尝试了WHERE c = 4的所有可能位置,但是它不起作用。感觉如果是MySQL而不是PostgresSQL,它会起作用。

有人知道如何解决吗?

2 个答案:

答案 0 :(得分:3)

它将是having而不是where

    SELECT title, COUNT(title) AS c FROM film
    JOIN inventory
    ON film.film_id = inventory.film_id     
    GROUP BY film.title 
    having COUNT(title)=4

用于聚合函数的HAVING子句

答案 1 :(得分:1)

  

如果要在where子句中使用C列,则也可以使用以下查询。

Error: cannot open "Users/akima/Documents/SQL/city.csv"