在下面的声明中:
SELECT CustomerID, Country
FROM Customers
GROUP BY Country
HAVING count(CustomerID)>7
我想返回具有 7 个以上客户 ID 的国家/地区的所有客户 ID。但它只为每个国家/地区返回 1 个 ID。
我需要执行以下操作才能获得我想要的内容:
SELECT CustomerID, Country
FROM Customers
WHERE Country in (SELECT Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID)>7)
谁能解释一下为什么?
最佳答案
您可以将其很好地构造为子查询的连接:
SELECT CustomerID
FROM Customers c
JOIN (
SELECT Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 7
) c2 on c.Country = c2.Country;
关于mysql - HAVING和GROUP BY一起使用时,SQL只做聚合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45333027/