如何 SELECT 客户在特定日期之前下订单
How to SELECT customers with orders before specific date
我有两个table。
Table 'customers': customer_id, date_register, name
Table 'orders': order_id, customer_id, order_date
现在我想要在特定日期之前有订单但在该日期之后没有订单的客户。
我正在使用这个查询:
SELECT customer_id
FROM orders
WHERE EXISTS (SELECT order_id
FROM orders
WHERE order_date <= '2020-05-12 23:59:59')
AND NOT EXISTS (SELECT order_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59')
但是我得到的结果是空的。
我应该使用什么 SQL 查询?
您可以尝试使用主查询和左连接中的子查询根据两个范围选择客户,然后检查不匹配的 ID
SELECT DISTINCT customer_id
FROM orders
LEFT JOIN
(SELECT DISTINCT customer_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59') t ON t.customer_id = orders.customer_id
AND orders.order_date <= '2020-05-12 23:59:59'
WHERE t.id IS NULL
您可以使用聚合并在 HAVING
子句中设置条件:
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < '2020-05-13';
我有两个table。
Table 'customers': customer_id, date_register, name
Table 'orders': order_id, customer_id, order_date
现在我想要在特定日期之前有订单但在该日期之后没有订单的客户。
我正在使用这个查询:
SELECT customer_id
FROM orders
WHERE EXISTS (SELECT order_id
FROM orders
WHERE order_date <= '2020-05-12 23:59:59')
AND NOT EXISTS (SELECT order_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59')
但是我得到的结果是空的。
我应该使用什么 SQL 查询?
您可以尝试使用主查询和左连接中的子查询根据两个范围选择客户,然后检查不匹配的 ID
SELECT DISTINCT customer_id
FROM orders
LEFT JOIN
(SELECT DISTINCT customer_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59') t ON t.customer_id = orders.customer_id
AND orders.order_date <= '2020-05-12 23:59:59'
WHERE t.id IS NULL
您可以使用聚合并在 HAVING
子句中设置条件:
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < '2020-05-13';