选择在特定时间段之前和之后存在的值

时间:2019-02-25 17:56:32

标签: mysql sql

我有一个简单的表,您也可以在SQL Fiddle here中找到该表:

CREATE TABLE Orders (
    Customer TEXT,
    Order_Date DATE

);

INSERT INTO Orders
(Customer, Order_Date)
VALUES 
("Customer A", "2017-05-23"),
("Customer B", "2018-09-10"),
("Customer B", "2018-12-14"),
("Customer A", "2019-01-03"),
("Customer A", "2019-02-15"),
("Customer C", "2017-09-04"),
("Customer B", "2019-01-09"),
("Customer A", "2019-02-16"),
("Customer C", "2019-02-12"),
("Customer B", "2018-01-03");

您可以看到该表显示了来自不同客户的订单日期。
我使用以下SQL获取所有在2019年2月下订单的客户:

SELECT Customer
FROM ORDERS
WHERE Order_Date >= "2019-02-01 00:00:00"
AND Order_Date < "2019-03-01 00:00:00"

到目前为止,所有这些都工作正常。


但是,现在我要实现的是,仅列出列出哪些客户

a)在2月

WHERE order in >= "2019-02-01 00:00:00" AND < "2018-03-01 00:00:00"


b)没有 12个月前

下订单
WHERE no order < "2019-02-01 00:00:00" AND >= "2018-01-02 00:00:00"


c)在此12个月内下订单

WHERE order in < "2018-01-02 00:00:00"


要实现此目的,我需要更改查询中的哪些内容?

1 个答案:

答案 0 :(得分:1)

这有点复杂,但是您可以使用group byhaving

SELECT o.Customer
FROM ORDERS o
GROUP BY o.Customer
HAVING SUM( o.Order_Date >= '2019-02-01' AND o.Order_Date < '2019-03-01' ) > 0 AND
       SUM( o.Order_Date >= '2018-01-02' AND o.Order_Date < '2019-02-01' ) = 0 AND
       SUM( o.Order_Date < '2018-01-02' ) > 0 ;