Mysql SQL-通过不同的条件聚合同一列
假设我有一张这样的桌子Mysql SQL-通过不同的条件聚合同一列,mysql,sql,Mysql,Sql,假设我有一张这样的桌子 |country| customer_id | order_id | | CA | 5 | 3 | | CA | 5 | 4 | | CA | 6 | 5 | | CA | 6 | 6 | | US | 2 | 7 | | US | 7 |
|country| customer_id | order_id |
| CA | 5 | 3 |
| CA | 5 | 4 |
| CA | 6 | 5 |
| CA | 6 | 6 |
| US | 2 | 7 |
| US | 7 | 8 |
| US | 7 | 9 |
| US | 7 | 10 |
| US | 2 | 11 |
我想写一个查询来填充一个表
| country | customers_w_2_orders | customers_w_2_plus_orders |
| CA | 2 | 0 |
| US | 1 | 1 |
其中,按国家/地区汇总2份订单的客户数量和3份订单的客户数量
这就是我所做的,它没有给我想要的结果
SELECT country, count(*) as cnt1, count(*) as cnt2
FROM Orders
GROUP BY country
HAVING cnt1=2 AND cnt2>2;
dbfiddle首先构建一个表,其中包含每个客户及其在每个国家/地区的订单数量,其中每行是国家/地区、客户id、订单数量 现在,您可以通过在派生表上分组来计算\u订单数为2或大于2的频率
select country, sum(num_orders = 2), sum(num_orders > 2)
from (
select country, customer_id, count(*) as num_orders
from Orders
group by country, customer_id
) t group by country
将无法获得OP想要的格式。您将生成一个稀疏表。您提供的查询在0.5毫秒内完成,这比其他答案要好。谢谢我很高兴能帮上忙。 country | cust_w_2_orders | cust_2_plus_orders :------ | --------------: | -----------------: CA | 2 | 0 US | 1 | 1
select country, sum(num_orders = 2), sum(num_orders > 2)
from (
select country, customer_id, count(*) as num_orders
from Orders
group by country, customer_id
) t group by country
SELECT country,
(select count(distinct(customer_id)) from Orders o where o.country = Orders.country and (select count(*) from Orders o2 where o2.country = orders.country and o2.customer_id = o.customer_id) = 2) as customers_w_2_orders,
(select count(distinct(customer_id)) from Orders o where o.country = Orders.country and (select count(*) from Orders o2 where o2.country = orders.country and o2.customer_id = o.customer_id) > 2) as customers_w_2_plus_orders
FROM Orders
GROUP BY country;