MediumNo. 1193

Monthly Transactions I — LeetCode 1193 Python Solution

Topics
Database
Reading time
3 min

Table schema

SQLTable schema
Table: Transactions +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +---------------+---------+ id is the primary key of this table. The table has information about incoming transactions.

Example

SQLExample
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| country       | varchar |
| state         | enum    |
| amount        | int     |
| trans_date    | date    |
+---------------+---------+
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enum of type ["approved", "declined"].

Python solution

PythonSolution
import duckdb
import pandas as pd

def solution(transactions: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Transactions", transactions)
    return con.execute("""SELECT
    DATE_FORMAT(trans_date, '%Y-%m') AS month,
    country,
    COUNT(1) AS trans_count,
    SUM(state = 'approved') AS approved_count,
    SUM(amount) AS trans_total_amount,
    SUM(IF(state = 'approved', amount, 0)) AS approved_total_amount
FROM Transactions
GROUP BY 1, 2;""").df()

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

Frequently asked questions

How hard is LeetCode 1193. Monthly Transactions I?

LeetCode 1193. Monthly Transactions I is rated Medium on LeetCode.

What topics does LeetCode 1193. Monthly Transactions I cover?

LeetCode 1193. Monthly Transactions I is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.