Monthly Transactions II — LeetCode 1205 Python Solution
MediumLeetCode PremiumDatabase
- Problem
- #1205
- Reading time
- 5 min
- Source
- leetcode.com
Table schema
SQL
Table: Transactions +----------------+---------+ | Column Name | Type | +----------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +----------------+---------+ id is the column of unique values of this table. The table has information about incoming transactions.Example
SQL
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| id | int |
| country | varchar |
| state | enum |
| amount | int |
| trans_date | date |
+----------------+---------+
id is the column of unique values of this table.
The table has information about incoming transactions.
The state column is an ENUM (category) of type ["approved", "declined"].Python solution
Python
import duckdb
import pandas as pd
def solution(transactions: pd.DataFrame, chargebacks: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Transactions", transactions)
con.register("Chargebacks", chargebacks)
return con.execute("""WITH
T AS (
SELECT * FROM Transactions
UNION
SELECT id, country, 'chargeback', amount, c.trans_date
FROM
Transactions AS t
JOIN Chargebacks AS c ON t.id = c.trans_id
)
SELECT
DATE_FORMAT(trans_date, '%Y-%m') AS month,
country,
SUM(state = 'approved') AS approved_count,
SUM(IF(state = 'approved', amount, 0)) AS approved_amount,
SUM(state = 'chargeback') AS chargeback_count,
SUM(IF(state = 'chargeback', amount, 0)) AS chargeback_amount
FROM T
GROUP BY 1, 2
HAVING approved_amount OR chargeback_amount;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1205. Monthly Transactions II?
- LeetCode 1205. Monthly Transactions II is rated Medium on LeetCode.
- What topics does LeetCode 1205. Monthly Transactions II cover?
- LeetCode 1205. Monthly Transactions II is tagged Database on LeetCode.
- Is LeetCode 1205. Monthly Transactions II a premium problem?
- Yes. LeetCode 1205. Monthly Transactions II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.