SQL: Different score in where where?

My order table looks like this:

id   fk_customer
1    34
2    34
3    34
4    7
5    7
6    8

I would like to select only those customers who have more than two orders.

However, this does not work:

SELECT * FROM order WHERE COUNT DISTINCT fk_customer > 2

Please advice!

thank

+5
source share
4 answers

Try the following:

SELECT fk_customer, COUNT(*)   
FROM dbo.[Order]
GROUP BY fk_customer
HAVING COUNT(*) > 2

Order is a reserved word in most SQL database systems - a bad choice for a table name ... in SQL Server, you need to put it in square brackets so that it clears it as the name of the object (and not the reserved word).

+10
source

try it

SELECT fk_customer FROM orders
GROUP BY fk_customer
HAVING COUNT(id) > 2
+1
source

COUNT WHERE, SQL . , , HAVING .

SELECT fk_customer, COUNT(*)    
  FROM dbo.[Order] 
 GROUP 
    BY fk_customer 
HAVING COUNT(*) > 2 
+1
SELECT fk_customer, COUNT(fk_customer) FROM [order]
GROUP BY fk_customer HAVING COUNT(*) > 2
0
source

All Articles