SQL - 通过不同的标准聚合相同的列

时间:2017-03-25 00:25:00

标签: mysql sql

假设我有一个 Orders 表,如下所示

matrix

我想编写一个查询来填充表格,

|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    |

汇总了2个订单的客户数量和按国家/地区划分3个订单的客户数量。

这就是我所做的,并没有给出我想要的结果..

| country | customers_w_2_orders | customers_w_2_plus_orders |
| CA      | 2                    | 0                         |
| US      | 1                    | 1                         |

3 个答案:

答案 0 :(得分:2)

constexpr
country | cust_w_2_orders | cust_2_plus_orders
:------ | --------------: | -----------------:
CA      |               2 |                  0
US      |               1 |                  1

dbfiddle here

答案 1 :(得分:1)

首先构建一个表格,其中包含每个客户及每个国家/地区的订单数量,其中每行为country, customer_id, number_of_orders

现在,您可以通过对派生表进行分组来计算number_of_orders为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

答案 2 :(得分:1)

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;