如何计算按属性分组的行,而该属性在特定日期之前尚未出现?

时间:2019-03-26 14:17:53

标签: mysql sql

假设表格订单

CREATE TABLE Orders (
order_id int(11),
customer_id int(11),
purchase_date datetime
)

我们需要以下报告:对于在这个月之前没有下订单的客户,每个客户下了多少个订单?

这是我当前正在使用的非常慢的sql:

SELECT count(order_id) num_of_orders, customer_id 
FROM   (SELECT order_id, customer_id
        FROM   orders 
        WHERE  customer_id NOT IN (SELECT DISTINCT customer_id 
                                   FROM   orders 
                                   WHERE  purchase_date < '2019-03-01')) a 
GROUP  BY customer_id;

是否有更快/更有效的方式编写此查询?

2 个答案:

答案 0 :(得分:2)

我将其重写为:

SELECT COUNT(order_id), customer_id
FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM orders o1 WHERE o1.customer_id = o.customer_id AND o1.purchase_date < '2019-03-01')
GROUP BY customer_id;

这要归功于订单索引(customer_id)。

但是,如果orders表包含null的{​​{1}},则customer_id子查询将返回NOT IN

答案 1 :(得分:1)

我不确定这会更快,但是更简单:

SELECT customer_id, count(*) as num_of_orders
FROM  orders o
GROUP BY customer_id
HAVING MIN(purchase_date) >= '2019-03-01';