2

Given a table tbl_orders containing order details for many months, what's the most efficient SQL query to get a list of user ID's userID who appear in a given period BETWEEN 2019-01-01 AND 2019-01-31 but don't appear in another period BETWEEN 2019-02-01 AND 2019-02-28.

Date column is orderDate

I tried self join but it returns nothing

SELECT DISTINCT a.userID
FROM tbl_orders a,
     tbl_orders b
WHERE a.orderDate BETWEEN 2019-01-01 AND 2021-01-31
  AND b.orderDate
    NOT BETWEEN 2019-02-01 AND 2019-02-28;
Taher Elhouderi
  • 233
  • 2
  • 11

2 Answers2

1

Possibly this one:

SELECT userID
FROM tbl_orders
WHERE orderDate BETWEEN '2019-01-01' AND '2019-02-28'
GROUP BY userID
HAVING MAX(orderDate) <= '2019-01-31'
ProDec
  • 5,390
  • 1
  • 3
  • 12
1

You can use NOT EXISTS

Your dates are wrong the must have a single quote

SELECT DISTINCT a.userID
FROM tbl_orders a 
WHERE a.orderDate BETWEEN '2019-01-01' AND '2021-01-31'
  AND NOT EXISTS(SELECT 1 FROM tbl_orders WHERE orderDate
    BETWEEN '2019-02-01' AND '2019-02-28');
nbk
  • 45,398
  • 8
  • 30
  • 47