查找出现在某个时期而不是另一个时期的用户 ID
Find user ID's who appear in a certain period and not in another
鉴于 table tbl_orders
包含多个月的订单详细信息,什么是最有效的 SQL 查询来获取出现在给定时期 BETWEEN 2019-01-01 AND 2019-01-31
但没有出现在另一个时期 BETWEEN 2019-02-01 AND 2019-02-28
.
日期列是 orderDate
我试过自行加入,但 returns 什么都没有
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;
可能是这个:
SELECT userID
FROM tbl_orders
WHERE orderDate BETWEEN '2019-01-01' AND '2019-02-28'
GROUP BY userID
HAVING MAX(orderDate) <= '2019-01-31'
您可以使用 NOT EXISTS
你的日期有误必须有单引号
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');
鉴于 table tbl_orders
包含多个月的订单详细信息,什么是最有效的 SQL 查询来获取出现在给定时期 BETWEEN 2019-01-01 AND 2019-01-31
但没有出现在另一个时期 BETWEEN 2019-02-01 AND 2019-02-28
.
日期列是 orderDate
我试过自行加入,但 returns 什么都没有
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;
可能是这个:
SELECT userID
FROM tbl_orders
WHERE orderDate BETWEEN '2019-01-01' AND '2019-02-28'
GROUP BY userID
HAVING MAX(orderDate) <= '2019-01-31'
您可以使用 NOT EXISTS
你的日期有误必须有单引号
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');