返回介绍

solution / 2700-2799 / 2752.Customers with Maximum Number of Transactions on Consecutive Days / README_EN

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

2752. Customers with Maximum Number of Transactions on Consecutive Days

中文文档

Description

Table: Transactions

+------------------+------+
| Column Name    | Type |
+------------------+------+
| transaction_id   | int  |
| customer_id    | int  |
| transaction_date | date |
| amount       | int  |
+------------------+------+
transaction_id is the column with unique values of this table.
Each row contains information about transactions that includes unique (customer_id, transaction_date) along with the corresponding customer_id and amount.   

Write a solution to find all customer_id who made the maximum number of transactions on consecutive days.

Return all customer_id with the maximum number of consecutive transactions. Order the result table by customer_id in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Transactions table:
+----------------+-------------+------------------+--------+
| transaction_id | customer_id | transaction_date | amount |
+----------------+-------------+------------------+--------+
| 1        | 101     | 2023-05-01     | 100  |
| 2        | 101     | 2023-05-02     | 150  |
| 3        | 101     | 2023-05-03     | 200  |
| 4        | 102     | 2023-05-01     | 50   |
| 5        | 102     | 2023-05-03     | 100  |
| 6        | 102     | 2023-05-04     | 200  |
| 7        | 105     | 2023-05-01     | 100  |
| 8        | 105     | 2023-05-02     | 150  |
| 9        | 105     | 2023-05-03     | 200  |
+----------------+-------------+------------------+--------+
Output: 
+-------------+
| customer_id | 
+-------------+
| 101     | 
| 105     | 
+-------------+
Explanation: 
- customer_id 101 has a total of 3 transactions, and all of them are consecutive.
- customer_id 102 has a total of 3 transactions, but only 2 of them are consecutive. 
- customer_id 105 has a total of 3 transactions, and all of them are consecutive.
In total, the highest number of consecutive transactions is 3, achieved by customer_id 101 and 105. The customer_id are sorted in ascending order.

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  s AS (
    SELECT
      customer_id,
      DATE_SUB(
        transaction_date,
        INTERVAL ROW_NUMBER() OVER (
          PARTITION BY customer_id
          ORDER BY transaction_date
        ) DAY
      ) AS transaction_date
    FROM Transactions
  ),
  t AS (
    SELECT customer_id, transaction_date, COUNT(1) AS cnt
    FROM s
    GROUP BY 1, 2
  )
SELECT customer_id
FROM t
WHERE cnt = (SELECT MAX(cnt) FROM t)
ORDER BY customer_id;

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

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

发布评论

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