HardNo. 2994LeetCode Premium
Friday Purchases II — LeetCode 2994 Python Solution
- Topics
- Database
- Reading time
- 5 min
- Source
- leetcode.com
Table schema
Table: Purchases +---------------+------+ | Column Name | Type | +---------------+------+ | user_id | int | | purchase_date | date | | amount_spend | int | +---------------+------+ (user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table. purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.Example
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user id, purchase date, and amount spend.Python solution
import duckdb
import pandas as pd
def solution(purchases: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Purchases", purchases)
return con.execute("""WITH RECURSIVE
T AS (
SELECT '2023-11-01' AS purchase_date
UNION
SELECT purchase_date + INTERVAL 1 DAY
FROM T
WHERE purchase_date < '2023-11-30'
)
SELECT
CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month,
purchase_date,
IFNULL(SUM(amount_spend), 0) AS total_amount
FROM
T
LEFT JOIN Purchases USING (purchase_date)
WHERE DAYOFWEEK(purchase_date) = 6
GROUP BY 2
ORDER BY 1;""").df()Complexity
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
Frequently asked questions
- How hard is LeetCode 2994. Friday Purchases II?
LeetCode 2994. Friday Purchases II is rated Hard on LeetCode.
- What topics does LeetCode 2994. Friday Purchases II cover?
LeetCode 2994. Friday Purchases II is tagged Database on LeetCode.
- Is LeetCode 2994. Friday Purchases II a premium problem?
Yes. LeetCode 2994. Friday Purchases II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.