我有问题。我有一个名为 customers
的 SQL 数据库,其中包含 3 列 Country
、CustomerID
和 Product
。使用该数据库,我想计算购买自行车、烧瓶和头盔产品但按国家/地区分组的所有客户,如下图所示。
你能帮我解决这个问题吗?我想我必须在同一个表上进行连接并使用另一个选择进行嵌套查询,但我真的不知道该怎么做。
非常感谢您的帮助!
答案 0 :(得分:2)
您可以将 HAVING
子句与 GROUP BY
一起使用,同时在对这三种产品进行计数后对每个客户进行明确计数,例如
SELECT Country, COUNT(DISTINCT CustomerID) AS Count
FROM customers
WHERE Product IN ('Bike','Flask','Helmet')
AND CustomerID IN ( SELECT CustomerID
FROM customers
GROUP BY CustomerID
HAVING COUNT(DISTINCT Product)=3 )
GROUP BY Country
答案 1 :(得分:2)
您必须分两步进行聚合。首先找到拥有 3 种不同产品的客户,然后统计这些客户。
SELECT country, count(*)
FROM
(
SELECT country, CustomerID
FROM customers
WHERE product IN ('Bike','Flask','Helmet')
GROUP BY country, CustomerID
HAVING COUNT(distinct product) = 3
) dt
GROUP BY country
答案 2 :(得分:0)
试试这个sql:
select Country,count(distinct CustomerID)
from customers
where Product in ('Bike','Flask','Helmet')
group by Country
答案 3 :(得分:0)
选择国家,计数(不同的客户ID) 来自客户 产品在 ('Bike','Flask','Helmet') 按国家分组
答案 4 :(得分:0)
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING Product in ('Bike','Flask','Helmet');