楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 2026-11-22 11:52:43 | 只看该作者
全局:
2837. Total Traveled Distance
Easy
Topics
SQL Schema
Pandas Schema
Table: Users

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| name        | varchar |
+-------------+---------+
user_id is the column with unique values for this table.
Each row of this table contains user id and name.
Table: Rides

+--------------+------+
| Column Name  | Type |
+--------------+------+
| ride_id      | int  |
| user_id      | int  |
| distance     | int  |
+--------------+------+
ride_id is the column of unique values for this table.
Each row of this table contains ride id, user id, and traveled distance.
Write a solution to calculate the distance traveled by each user. If there is a user who hasn't completed any rides, then their distance should be considered as 0. Output the user_id, name and total traveled distance.

Return the result table ordered by user_id in ascending order.

The result format is in the following example.



Example 1:

Input:
Users table:
+---------+---------+
| user_id | name    |
+---------+---------+
| 17      | Addison |
| 14      | Ethan   |
| 4       | Michael |
| 2       | Avery   |
| 10      | Eleanor |
+---------+---------+
Rides table:
+---------+---------+----------+
| ride_id | user_id | distance |
+---------+---------+----------+
| 72      | 17      | 160      |
| 42      | 14      | 161      |
| 45      | 4       | 59       |
| 32      | 2       | 197      |
| 15      | 4       | 357      |
| 56      | 2       | 196      |
| 10      | 14      | 25       |
+---------+---------+----------+
Output:
+---------+---------+-------------------+
| user_id | name    | traveled distance |
+---------+---------+-------------------+
| 2       | Avery   | 393               |
| 4       | Michael | 416               |
| 10      | Eleanor | 0                 |
| 14      | Ethan   | 186               |
| 17      | Addison | 160               |
+---------+---------+-------------------+
Explanation:
-  User id 2 completed two journeys of 197 and 196, resulting in a combined travel distance of 393.
-  User id 4 completed two journeys of 59 and 357, resulting in a combined travel distance of 416.
-  User id 14 completed two journeys of 161 and 25, resulting in a combined travel distance of 186.
-  User id 16 completed only one journey of 160.
-  User id 10 did not complete any journeys, thus the total travel distance remains at 0.
Returning the table orderd by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT u.user_id,
  3.        u.name,
  4.        COALESCE(SUM(r.distance), 0) AS `traveled distance`
  5. FROM Users u
  6. LEFT JOIN Rides r
  7.   ON u.user_id = r.user_id
  8. GROUP BY u.user_id, u.name
  9. ORDER BY u.user_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:53:20 | 只看该作者
全局:
2853. Highest Salaries Difference
Easy
Topics
SQL Schema
Pandas Schema
Table: Salaries

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| emp_name    | varchar |
| department  | varchar |
| salary      | int     |
+-------------+---------+
(emp_name, department) is the primary key (combination of unique values) for this table.
Each row of this table contains emp_name, department and salary. There will be at least one entry for the engineering and marketing departments.
Write a solution to calculate the difference between the highest salaries in the marketing and engineering department. Output the absolute difference in salaries.

Return the result table.

The result format is in the following example.



Example 1:

Input:
Salaries table:
+----------+-------------+--------+
| emp_name | department  | salary |
+----------+-------------+--------+
| Kathy    | Engineering | 50000  |
| Roy      | Marketing   | 30000  |
| Charles  | Engineering | 45000  |
| Jack     | Engineering | 85000  |
| Benjamin | Marketing   | 34000  |
| Anthony  | Marketing   | 42000  |
| Edward   | Engineering | 102000 |
| Terry    | Engineering | 44000  |
| Evelyn   | Marketing   | 53000  |
| Arthur   | Engineering | 32000  |
+----------+-------------+--------+
Output:
+-------------------+
| salary_difference |
+-------------------+
| 49000             |
+-------------------+
Explanation:
- The Engineering and Marketing departments have the highest salaries of 102,000 and 53,000, respectively. Resulting in an absolute difference of 49,000.
  1. # Write your MySQL query statement below
  2. SELECT ABS(
  3.            MAX(CASE WHEN department = 'Marketing'   THEN salary END)
  4.          - MAX(CASE WHEN department = 'Engineering' THEN salary END)
  5.        ) AS salary_difference
  6. FROM Salaries;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:53:59 | 只看该作者
全局:
2854. Rolling Average Steps
Medium
Topics
SQL Schema
Pandas Schema
Table: Steps

+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| steps_count | int  |
| steps_date  | date |
+-------------+------+
(user_id, steps_date) is the primary key for this table.
Each row of this table contains user_id, steps_count, and steps_date.
Write a solution to calculate 3-day rolling averages of steps for each user.

We calculate the n-day rolling average this way:

For each day, we calculate the average of n consecutive days of step counts ending on that day if available, otherwise, n-day rolling average is not defined for it.
Output the user_id, steps_date, and rolling average. Round the rolling average to two decimal places.

Return the result table ordered by user_id, steps_date in ascending order.

The result format is in the following example.



Example 1:

Input:
Steps table:
+---------+-------------+------------+
| user_id | steps_count | steps_date |
+---------+-------------+------------+
| 1       | 687         | 2021-09-02 |
| 1       | 395         | 2021-09-04 |
| 1       | 499         | 2021-09-05 |
| 1       | 712         | 2021-09-06 |
| 1       | 576         | 2021-09-07 |
| 2       | 153         | 2021-09-06 |
| 2       | 171         | 2021-09-07 |
| 2       | 530         | 2021-09-08 |
| 3       | 945         | 2021-09-04 |
| 3       | 120         | 2021-09-07 |
| 3       | 557         | 2021-09-08 |
| 3       | 840         | 2021-09-09 |
| 3       | 627         | 2021-09-10 |
| 5       | 382         | 2021-09-05 |
| 6       | 480         | 2021-09-01 |
| 6       | 191         | 2021-09-02 |
| 6       | 303         | 2021-09-05 |
+---------+-------------+------------+
Output:
+---------+------------+-----------------+
| user_id | steps_date | rolling_average |
+---------+------------+-----------------+
| 1       | 2021-09-06 | 535.33          |
| 1       | 2021-09-07 | 595.67          |
| 2       | 2021-09-08 | 284.67          |
| 3       | 2021-09-09 | 505.67          |
| 3       | 2021-09-10 | 674.67          |   
+---------+------------+-----------------+
Explanation:
- For user id 1, the step counts for the three consecutive days up to 2021-09-06 are available. Consequently, the rolling average for this particular date is computed as (395 + 499 + 712) / 3 = 535.33.
- For user id 1, the step counts for the three consecutive days up to 2021-09-07 are available. Consequently, the rolling average for this particular date is computed as (499 + 712 + 576) / 3 = 595.67.
- For user id 2, the step counts for the three consecutive days up to 2021-09-08 are available. Consequently, the rolling average for this particular date is computed as (153 + 171 + 530) / 3 = 284.67.
- For user id 3, the step counts for the three consecutive days up to 2021-09-09 are available. Consequently, the rolling average for this particular date is computed as (120 + 557 + 840) / 3 = 505.67.
- For user id 3, the step counts for the three consecutive days up to 2021-09-10 are available. Consequently, the rolling average for this particular date is computed as (557 + 840 + 627) / 3 = 674.67.
- For user id 4 and 5, the calculation of the rolling average is not viable as there is insufficient data for the consecutive three days. Output table ordered by user_id and steps_date in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT user_id,
  3.        steps_date,
  4.        ROUND(avg_steps, 2) AS rolling_average
  5. FROM (
  6.     SELECT user_id,
  7.            steps_date,
  8.            AVG(steps_count) OVER w AS avg_steps,
  9.            COUNT(*) OVER w         AS cnt
  10.     FROM Steps
  11.     WINDOW w AS (
  12.         PARTITION BY user_id
  13.         ORDER BY steps_date
  14.         RANGE BETWEEN INTERVAL 2 DAY PRECEDING AND CURRENT ROW
  15.     )
  16. ) t
  17. WHERE cnt = 3
  18. ORDER BY user_id, steps_date;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 12:04:43 | 只看该作者
全局:
2124. Check if All A's Appears Before All B's
Solved
Easy
Topics
conpanies icon
Companies
Hint
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.



Example 1:

Input: s = "aaabbb"
Output: true
Explanation:
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears before every 'b' and we return true.
Example 2:

Input: s = "abab"
Output: false
Explanation:
There is an 'a' at index 2 and a 'b' at index 1.
Hence, not every 'a' appears before every 'b' and we return false.
Example 3:

Input: s = "bbb"
Output: true
Explanation:
There are no 'a's, hence, every 'a' appears before every 'b' and we return true.


Constraints:

1 <= s.length <= 100
s[i] is either 'a' or 'b'.

我的解法
  1. class Solution:
  2.     def checkString(self, s: str) -> bool:
  3.         last_a = -1
  4.         first_b = -1

  5.         for ind, val in enumerate(s):
  6.             if val == 'a':
  7.                 last_a = ind

  8.             if val == 'b' and first_b == -1:
  9.                 first_b = ind

  10.             if last_a > first_b and first_b != -1:

  11.                 return False
  12.             
  13.         return True
复制代码
时间复杂度 O(n),空间复杂度 O(1)。

原理:

first_b 记录第一个 'b' 出现的下标。
last_a 记录最近一个 'a' 出现的下标。
如果在第一个 'b' 出现之后又遇到了 'a',就会有 last_a > first_b,这正是违反题意的情况,直接返回 False。
first_b != -1 这个判断是必须的。否则像 "aaa" 这种没有 'b' 的字符串,last_a > -1 会误判为 False。

优化

写法一:只用一个标志位
  1. class Solution:
  2.     def checkString(self, s: str) -> bool:
  3.         seen_b = False
  4.         for c in s:
  5.             if c == 'b':
  6.                 seen_b = True
  7.             elif seen_b:  # 在 'b' 之后又出现了 'a'
  8.                 return False
  9.         return True
复制代码
写法二:找指纹字符子串

合法的字符串形如 a*b*(若干个 a 后面跟着若干个 b)。只要 'b' 后面紧跟着 'a',就破坏了这个结构。反过来,如果某个 'a' 出现在某个 'b' 之后,那么字符串中一定会出现相邻的 "ba"。所以只需要检查字符串里有没有 "ba" 即可。
  1. class Solution:
  2.     def checkString(self, s: str) -> bool:
  3.         return "ba" not in s
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:48:19 | 只看该作者
全局:
2893. Calculate Orders Within Each Interval
Medium
Topics
SQL Schema
Pandas Schema
Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| minute      | int  |
| order_count | int  |
+-------------+------+
minute is the primary key for this table.
Each row of this table contains the minute and number of orders received during that specific minute. The total number of rows will be a multiple of 6.
Write a query to calculate total orders within each interval. Each interval is defined as a combination of 6 minutes.

Minutes 1 to 6 fall within interval 1, while minutes 7 to 12 belong to interval 2, and so forth.
Return the result table ordered by interval_no in ascending order.

The result format is in the following example.



Example 1:

Input:
Orders table:
+--------+-------------+
| minute | order_count |
+--------+-------------+
| 1      | 0           |
| 2      | 2           |
| 3      | 4           |
| 4      | 6           |
| 5      | 1           |
| 6      | 4           |
| 7      | 1           |
| 8      | 2           |
| 9      | 4           |
| 10     | 1           |
| 11     | 4           |
| 12     | 6           |
+--------+-------------+
Output:
+-------------+--------------+
| interval_no | total_orders |
+-------------+--------------+
| 1           | 17           |
| 2           | 18           |   
+-------------+--------------+
Explanation:
- Interval number 1 comprises minutes from 1 to 6. The total orders in these six minutes are (0 + 2 + 4 + 6 + 1 + 4) = 17.
- Interval number 2 comprises minutes from 7 to 12. The total orders in these six minutes are (1 + 2 + 4 + 1 + 4 + 6) = 18.
Returning table orderd by interval_no in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     CEIL(minute / 6) AS interval_no,
  4.     SUM(order_count) AS total_orders
  5. FROM Orders
  6. GROUP BY interval_no
  7. ORDER BY interval_no;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:49:25 | 只看该作者
全局:
2922. Market Analysis III
Medium
Topics
SQL Schema
Table: Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| seller_id      | int     |
| join_date      | date    |
| favorite_brand | varchar |
+----------------+---------+
seller_id is column of unique values for this table.
This table contains seller id, join date, and favorite brand of sellers.
Table: Items

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| item_id       | int     |
| item_brand    | varchar |
+---------------+---------+
item_id is the column of unique values for this table.
This table contains item id and item brand.
Table: Orders

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| item_id       | int     |
| seller_id     | int     |
+---------------+---------+
order_id is the column of unique values for this table.
item_id is a foreign key to the Items table.
seller_id is a foreign key to the Users table.
This table contains order id, order date, item id and seller id.
Write a solution to find the top seller who has sold the highest number of unique items with a different brand than their favorite brand. If there are multiple sellers with the same highest count, return all of them.

Return the result table ordered by seller_id in ascending order.

The result format is in the following example.



Example 1:

Input:
Users table:
+-----------+------------+----------------+
| seller_id | join_date  | favorite_brand |
+-----------+------------+----------------+
| 1         | 2019-01-01 | Lenovo         |
| 2         | 2019-02-09 | Samsung        |
| 3         | 2019-01-19 | LG             |
+-----------+------------+----------------+
Orders table:
+----------+------------+---------+-----------+
| order_id | order_date | item_id | seller_id |
+----------+------------+---------+-----------+
| 1        | 2019-08-01 | 4       | 2         |
| 2        | 2019-08-02 | 2       | 3         |
| 3        | 2019-08-03 | 3       | 3         |
| 4        | 2019-08-04 | 1       | 2         |
| 5        | 2019-08-04 | 4       | 2         |
+----------+------------+---------+-----------+
Items table:
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1       | Samsung    |
| 2       | Lenovo     |
| 3       | LG         |
| 4       | HP         |
+---------+------------+
Output:
+-----------+-----------+
| seller_id | num_items |
+-----------+-----------+
| 2         | 1         |
| 3         | 1         |
+-----------+-----------+
Explanation:
- The user with seller_id 2 has sold three items, but only two of them are not marked as a favorite. We will include a unique count of 1 because both of these items are identical.
- The user with seller_id 3 has sold two items, but only one of them is not marked as a favorite. We will include just that non-favorite item in our count.
Since seller_ids 2 and 3 have the same count of one item each, they both will be displayed in the output.
  1. # Write your MySQL query statement below
  2. WITH seller_counts AS (
  3.     SELECT
  4.         o.seller_id,
  5.         COUNT(DISTINCT o.item_id) AS num_items
  6.     FROM Orders o
  7.     JOIN Items i ON o.item_id = i.item_id
  8.     JOIN Users u ON o.seller_id = u.seller_id
  9.     WHERE i.item_brand <> u.favorite_brand
  10.     GROUP BY o.seller_id
  11. )
  12. SELECT
  13.     seller_id,
  14.     num_items
  15. FROM seller_counts
  16. WHERE num_items = (SELECT MAX(num_items) FROM seller_counts)
  17. ORDER BY seller_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:55:52 | 只看该作者
全局:
2978. Symmetric Coordinates
Medium
Topics
SQL Schema
Pandas Schema
Table: Coordinates

+-------------+------+
| Column Name | Type |
+-------------+------+
| X           | int  |
| Y           | int  |
+-------------+------+
Each row includes X and Y, where both are integers. Table may contain duplicate values.
Two coordindates (X1, Y1) and (X2, Y2) are said to be symmetric coordintes if X1 == Y2 and X2 == Y1.

Write a solution that outputs, among all these symmetric coordintes, only those unique coordinates that satisfy the condition X1 <= Y1.

Return the result table ordered by X and Y (respectively) in ascending order.

The result format is in the following example.



Example 1:

Input:
Coordinates table:
+----+----+
| X  | Y  |
+----+----+
| 20 | 20 |
| 20 | 20 |
| 20 | 21 |
| 23 | 22 |
| 22 | 23 |
| 21 | 20 |
+----+----+
Output:
+----+----+
| x  | y  |
+----+----+
| 20 | 20 |
| 20 | 21 |
| 22 | 23 |
+----+----+
Explanation:
- (20, 20) and (20, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. This results in displaying (20, 20) as a distinctive coordinates.
- (20, 21) and (21, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (20, 21) will be displayed because X1 <= Y1.
- (23, 22) and (22, 23) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (22, 23) will be displayed because X1 <= Y1.
The output table is sorted by X and Y in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT DISTINCT c1.X AS x, c1.Y AS y
  3. FROM Coordinates c1
  4. JOIN Coordinates c2
  5.   ON c1.X = c2.Y AND c1.Y = c2.X
  6. WHERE c1.X < c1.Y

  7. UNION

  8. SELECT X AS x, Y AS y
  9. FROM Coordinates
  10. WHERE X = Y
  11. GROUP BY X, Y
  12. HAVING COUNT(*) > 1

  13. ORDER BY x, y;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:57:06 | 只看该作者
全局:
2984. Find Peak Calling Hours for Each City
Medium
Topics
SQL Schema
Pandas Schema
Table: Calls

+--------------+----------+
| Column Name  | Type     |
+--------------+----------+
| caller_id    | int      |
| recipient_id | int      |
| call_time    | datetime |
| city         | varchar  |
+--------------+----------+
(caller_id, recipient_id, call_time) is the primary key (combination of columns with unique values) for this table.
Each row contains caller id, recipient id, call time, and city.
Write a solution to find the peak calling hour for each city. If multiple hours have the same number of calls, all of those hours will be recognized as peak hours for that specific city.

Return the result table ordered by peak calling hour and city in descending order.

The result format is in the following example.



Example 1:

Input:
Calls table:
+-----------+--------------+---------------------+----------+
| caller_id | recipient_id | call_time           | city     |
+-----------+--------------+---------------------+----------+
| 8         | 4            | 2021-08-24 22:46:07 | Houston  |
| 4         | 8            | 2021-08-24 22:57:13 | Houston  |  
| 5         | 1            | 2021-08-11 21:28:44 | Houston  |  
| 8         | 3            | 2021-08-17 22:04:15 | Houston  |
| 11        | 3            | 2021-08-17 13:07:00 | New York |
| 8         | 11           | 2021-08-17 14:22:22 | New York |
+-----------+--------------+---------------------+----------+
Output:
+----------+-------------------+-----------------+
| city     | peak_calling_hour | number_of_calls |
+----------+-------------------+-----------------+
| Houston  | 22                | 3               |
| New York | 14                | 1               |
| New York | 13                | 1               |
+----------+-------------------+-----------------+
Explanation:
For Houston:
  - The peak time is 22:00, with a total of 3 calls recorded.
For New York:
  - Both 13:00 and 14:00 hours have equal call counts of 1, so both times are considered peak hours.
Output table is ordered by peak_calling_hour and city in descending order.
  1. # Write your MySQL query statement below
  2. WITH hourly AS (
  3.     SELECT
  4.         city,
  5.         HOUR(call_time) AS peak_calling_hour,
  6.         COUNT(*) AS number_of_calls
  7.     FROM Calls
  8.     GROUP BY city, HOUR(call_time)
  9. )
  10. SELECT city, peak_calling_hour, number_of_calls
  11. FROM (
  12.     SELECT
  13.         city,
  14.         peak_calling_hour,
  15.         number_of_calls,
  16.         RANK() OVER (PARTITION BY city ORDER BY number_of_calls DESC) AS rk
  17.     FROM hourly
  18. ) t
  19. WHERE rk = 1
  20. ORDER BY peak_calling_hour DESC, city DESC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:57:52 | 只看该作者
全局:
2985. Calculate Compressed Mean
Easy
Topics
SQL Schema
Pandas Schema
Table: Orders

+-------------------+------+
| Column Name       | Type |
+-------------------+------+
| order_id          | int  |
| item_count        | int  |
| order_occurrences | int  |
+-------------------+------+
order_id is column of unique values for this table.
This table contains order_id, item_count, and order_occurrences.
Write a solution to calculate the average number of items per order, rounded to 2 decimal places.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Orders table:
+----------+------------+-------------------+
| order_id | item_count | order_occurrences |
+----------+------------+-------------------+
| 10       | 1          | 500               |
| 11       | 2          | 1000              |     
| 12       | 3          | 800               |  
| 13       | 4          | 1000              |
+----------+------------+-------------------+
Output
+-------------------------+
| average_items_per_order |
+-------------------------+
| 2.70                    |
+-------------------------+
Explanation
The calculation is as follows:
- Total items: (1 * 500) + (2 * 1000) + (3 * 800) + (4 * 1000) = 8900
- Total orders: 500 + 1000 + 800 + 1000 = 3300
- Therefore, the average items per order is 8900 / 3300 = 2.70
  1. # Write your MySQL query statement below
  2. SELECT
  3.     ROUND(SUM(item_count * order_occurrences) / SUM(order_occurrences), 2) AS average_items_per_order
  4. FROM Orders;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 11:58:35 | 只看该作者
全局:
2986. Find Third Transaction
Medium
Topics
SQL Schema
Pandas Schema
Table: Transactions

+------------------+----------+
| Column Name      | Type     |
+------------------+----------+
| user_id          | int      |
| spend            | decimal  |
| transaction_date | datetime |
+------------------+----------+
(user_id, transaction_date) is column of unique values for this table.
This table contains user_id, spend, and transaction_date.
Write a solution to find the third transaction (if they have at least three transactions) of every user, where the spending on the preceding two transactions is lower than the spending on the third transaction.

Return the result table by user_id in ascending order.

The result format is in the following example.



Example 1:

Input:
Transactions table:
+---------+--------+---------------------+
| user_id | spend  | transaction_date    |
+---------+--------+---------------------+
| 1       | 65.56  | 2023-11-18 13:49:42 |
| 1       | 96.0   | 2023-11-30 02:47:26 |     
| 1       | 7.44   | 2023-11-02 12:15:23 |
| 1       | 49.78  | 2023-11-12 00:13:46 |
| 2       | 40.89  | 2023-11-21 04:39:15 |  
| 2       | 100.44 | 2023-11-20 07:39:34 |
| 3       | 37.33  | 2023-11-03 06:22:02 |
| 3       | 13.89  | 2023-11-11 16:00:14 |
| 3       | 7.0    | 2023-11-29 22:32:36 |
+---------+--------+---------------------+
Output
+---------+-------------------------+------------------------+
| user_id | third_transaction_spend | third_transaction_date |
+---------+-------------------------+------------------------+
| 1       | 65.56                   | 2023-11-18 13:49:42    |  
+---------+-------------------------+------------------------+
Explanation
- For user_id 1, their third transaction occurred on 2023-11-18 at 13:49:42 with an amount of $65.56, surpassing the expenditures of the previous two transactions which were $7.44 on 2023-11-02 at 12:15:23 and $49.78 on 2023-11-12 at 00:13:46. Thus, this third transaction will be included in the output table.
- user_id 2 only has a total of 2 transactions, so there isn't a third transaction to consider.
- For user_id 3, the amount of $7.0 for their third transaction is less than that of the preceding two transactions, so it won't be included.
Output table is ordered by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH t AS (
  3.     SELECT
  4.         user_id,
  5.         spend,
  6.         transaction_date,
  7.         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_date) AS rn,
  8.         LAG(spend, 1) OVER (PARTITION BY user_id ORDER BY transaction_date) AS prev1,
  9.         LAG(spend, 2) OVER (PARTITION BY user_id ORDER BY transaction_date) AS prev2
  10.     FROM Transactions
  11. )
  12. SELECT
  13.     user_id,
  14.     spend AS third_transaction_spend,
  15.     transaction_date AS third_transaction_date
  16. FROM t
  17. WHERE rn = 3
  18.   AND spend > prev1
  19.   AND spend > prev2
  20. ORDER BY user_id;
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表