3

我有一张包含所有购买物品的表格。

我需要检查哪些用户在特定时间段内(比如 2013 年 3 月 21 日到 2013 年 4 月 21 日)购买了商品,之后再没有购买过任何东西。

我可以选择在那段时间购买过物品的用户,但我不知道如何过滤那些在那之后从未购买过任何东西的用户......

SELECT `userId`, `email` FROM my_table 
WHERE `date` BETWEEN '2013-03-21' AND '2013-04-21' GROUP BY `userId`
4

6 回答 6

3

试试这个

SELECT 
  user_id
FROM 
  my_table 
WHERE 
  purchase_date >= '2012-05-01'        --your_start_date
GROUP BY 
  user_id
HAVING 
  max(purchase_date) <= '2012-06-01';  --your_end_date

它的工作原理是获取所有记录>= start date,将结果集分组user_id,然后找到max每个用户的购买日期。购买日期max应该是。<=end date由于此查询不使用 ajoin/inner query它可能会更快

测试数据

CREATE table user_purchases(user_id int, purchase_date date);
insert into user_purchases values (1, '2012-05-01');
insert into user_purchases values (2, '2012-05-06');
insert into user_purchases values (3, '2012-05-20');
insert into user_purchases values (4, '2012-06-01');
insert into user_purchases values (4, '2012-09-06');
insert into user_purchases values (1, '2012-09-06');

输出

| USER_ID |
-----------
|       2 |
|       3 |

SQLFIDDLE

于 2013-07-18T15:31:56.240 回答
2

这可能是实现这一目标的标准方法:

SELECT `userId`, `email` FROM my_table mt
WHERE `date` BETWEEN '2013-03-21' AND '2013-04-21' 
AND NOT EXISTS (
    SELECT * FROM my_table mt2 WHERE 
        mt2.`userId` = mt.`userId` 
        and mt2.`date` > '2013-04-21' 
)
GROUP BY `userId`
于 2013-07-18T15:05:17.413 回答
1

您必须分两个阶段进行 - 一个查询获取在该时间段内购买的用户列表,然后另一个查询获取该用户列表并查看他们之后是否购买了任何东西,例如

SELECT userID, email, count(after.*) AS purchases
FROM my_table AS after
LEFT JOIN (
    SELECT DISTINCT userID
    FROM my_table
    WHERE `date` BETWEEN '2013-03-21' AND '2013-04-21'
) AS during ON after.userID = during.userID
WHERE after.date > '2013-04-21'
HAVING purchases = 0;

内部查询获取在此期间至少购买了一件东西的用户 ID 列表。然后将该列表与同一张表结合起来,但在 period 之后过滤购买,并计算他们进行了多少购买,并过滤到只有那些“之后”购买为 0 的用户。

可能不会像写的那样工作——我的早茶还没喝。

于 2013-07-18T15:04:00.153 回答
1

尝试以下

 SELECT `userId`, `email` 
 FROM my_table WHERE `date` BETWEEN '2013-03-21' AND '2013-04-21' 
 and user_id not in 
    (select user_id from my_table 
     where `date` < '2013-03-21' or `date` > '2013-04-21' ) 
 GROUP BY `userId`
于 2013-07-18T15:04:53.177 回答
1

 SELECT `userId`, `email` FROM my_table WHERE (`date` BETWEEN '2013-03-21' AND '2013-04-21') and `date` >= '2013-04-21'  GROUP BY `userId`

这将仅选择在该时间范围内购买并在该时间范围之后购买的用户

希望这可以帮助。

于 2013-07-18T15:05:24.550 回答
1
SELECT 
    a.userId,
    a.email 
FROM
    my_table AS a 
WHERE a.date BETWEEN '2013-03-21' 
    AND '2013-04-21' 
    AND a.userId NOT IN 
    (SELECT 
        b.userId
    FROM
        my_table AS b 
    WHERE b.date BETWEEN '2013-04-22' 
        AND CURDATE() 
    GROUP BY b.userId) 
GROUP BY a.userId

这会过滤掉从结束日期到现在没有购买任何东西的任何人。

于 2013-07-18T15:08:29.103 回答