Reputation: 5471
I have the following simple table which you can also find in the 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");
As you can see the table displays the order dates from different customers.
I use the below SQL to get the all customers that placed an order in February 2019:
SELECT Customer
FROM ORDERS
WHERE Order_Date >= "2019-02-01 00:00:00"
AND Order_Date < "2019-03-01 00:00:00"
All this works fine so far.
However, now I want to achieve that only customers are listed which
a) placed an order in February and
WHERE order in >= "2019-02-01 00:00:00" AND < "2018-03-01 00:00:00"
b) did not place an order in the 12 month before and
WHERE no order < "2019-02-01 00:00:00" AND >= "2018-01-02 00:00:00"
c) placed an order before this 12 month period
WHERE order in < "2018-01-02 00:00:00"
What do I need to change in my query to achieve this?
Upvotes: 1
Views: 249
Reputation: 1269823
That is a bit complicated, but you can use group by
and having
:
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 ;
Upvotes: 1