返回介绍

solution / 2200-2299 / 2228.Users With Two Purchases Within Seven Days / README_EN

发布于 2024-06-17 01:03:08 字数 2338 浏览 0 评论 0 收藏 0

2228. Users With Two Purchases Within Seven Days

中文文档

Description

Table: Purchases

+---------------+------+
| Column Name   | Type |
+---------------+------+
| purchase_id   | int  |
| user_id     | int  |
| purchase_date | date |
+---------------+------+
purchase_id contains unique values.
This table contains logs of the dates that users purchased from a certain retailer.

 

Write a solution to report the IDs of the users that made any two purchases at most 7 days apart.

Return the result table ordered by user_id.

The result format is in the following example.

 

Example 1:

Input: 
Purchases table:
+-------------+---------+---------------+
| purchase_id | user_id | purchase_date |
+-------------+---------+---------------+
| 4       | 2     | 2022-03-13  |
| 1       | 5     | 2022-02-11  |
| 3       | 7     | 2022-06-19  |
| 6       | 2     | 2022-03-20  |
| 5       | 7     | 2022-06-19  |
| 2       | 2     | 2022-06-08  |
+-------------+---------+---------------+
Output: 
+---------+
| user_id |
+---------+
| 2     |
| 7     |
+---------+
Explanation: 
User 2 had two purchases on 2022-03-13 and 2022-03-20. Since the second purchase is within 7 days of the first purchase, we add their ID.
User 5 had only 1 purchase.
User 7 had two purchases on the same day so we add their ID.

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  t AS (
    SELECT
      user_id,
      DATEDIFF(
        purchase_date,
        LAG(purchase_date, 1) OVER (
          PARTITION BY user_id
          ORDER BY purchase_date
        )
      ) AS d
    FROM Purchases
  )
SELECT DISTINCT user_id
FROM t
WHERE d <= 7
ORDER BY user_id;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文