[英]SQL: Distinct count in where clause?
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 2 orders. 我想只选择订单超过2个的客户。
This doesnt work however: 但这不起作用:
SELECT * FROM order WHERE COUNT DISTINCT fk_customer > 2
Please advice! 请指教!
thanks 谢谢
Try this: 试试这个:
SELECT fk_customer, COUNT(*)
FROM dbo.[Order]
GROUP BY fk_customer
HAVING COUNT(*) > 2
Order
is a reserved word in most SQL based database systems - bad choice for a table name.... in SQL Server, you need to put it in square brackets to make it clear it's an object name (not the reserved word) to be used. 在大多数基于SQL的数据库系统中, Order
是一个保留字 - 对于表名称的错误选择....在SQL Server中,您需要将其放在方括号中以使其清楚它是一个对象名称(而不是保留字)用过的。
Try this 试试这个
SELECT fk_customer FROM orders
GROUP BY fk_customer
HAVING COUNT(id) > 2
If you try to use COUNT
in the WHERE
clause, SQL will throw an exception. 如果您尝试在WHERE
子句中使用COUNT
,SQL将引发异常。 You can only use an aggregate function if it is within a sub-query contained in a HAVING
clause or a select list. 如果聚合函数位于HAVING
子句或选择列表中包含的子查询中,则只能使用聚合函数。
SELECT fk_customer, COUNT(*)
FROM dbo.[Order]
GROUP
BY fk_customer
HAVING COUNT(*) > 2
SELECT fk_customer, COUNT(fk_customer) FROM [order]
GROUP BY fk_customer HAVING COUNT(*) > 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.