inblog logo
|
silver
    SQL문제풀기

    [SQL문제풀기] Monthly Transactions I

    silver's avatar
    silver
    Oct 27, 2025
    [SQL문제풀기] Monthly Transactions I
    Contents
    문제MySQL

    문제

    Monthly Transactions I - LeetCode
    Can you solve this real interview question? Monthly Transactions I - 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. The state column is an enum of type ["approved", "declined"].   Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount. Return the result table in any order. The query result format is in the following example.   Example 1: Input: Transactions table: +------+---------+----------+--------+------------+ | id | country | state | amount | trans_date | +------+---------+----------+--------+------------+ | 121 | US | approved | 1000 | 2018-12-18 | | 122 | US | declined | 2000 | 2018-12-19 | | 123 | US | approved | 2000 | 2019-01-01 | | 124 | DE | approved | 2000 | 2019-01-07 | +------+---------+----------+--------+------------+ Output: +----------+---------+-------------+----------------+--------------------+-----------------------+ | month | country | trans_count | approved_count | trans_total_amount | approved_total_amount | +----------+---------+-------------+----------------+--------------------+-----------------------+ | 2018-12 | US | 2 | 1 | 3000 | 1000 | | 2019-01 | US | 1 | 1 | 2000 | 2000 | | 2019-01 | DE | 1 | 1 | 2000 | 2000 | +----------+---------+-------------+----------------+--------------------+-----------------------+
    Monthly Transactions I - LeetCode
    https://leetcode.com/problems/monthly-transactions-i/description/?envType=study-plan-v2&envId=top-sql-50
    Monthly Transactions I - LeetCode

    MySQL

    내가 작성한 정답

    select date_format(trans_date,'%Y-%m') month, country, count(id) trans_count, sum(case when state = 'approved' then 1 else 0 end) approved_count, sum(amount) trans_total_amount, sum(case when state = 'approved' then amount else 0 end) approved_total_amount from Transactions group by date_format(trans_date,'%Y-%m'), country;
    Share article

    silver

    RSS·Powered by Inblog