Monthly Transactions I LeetCode Solution

Last updated on October 9th, 2024 at 10:16 pm

This Leetcode problem Monthly Transactions I LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

Monthly Transactions I LeetCode Solution

Monthly Transactions I LeetCode Solution

Problem Statement

Column NameType
idint
countryvarchar
stateenum
amountint
trans_datedate
Table: Transactions

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:

idcountrystate amount trans_date
121USapproved10002018-12-18
122USdeclined20002018-12-19
123USapproved20002019-01-01
124DEapproved20002019-01-07
Transactions table:

Output:

monthcountrytrans_countapproved_count trans_total_amount approved_total_amount
2018-12US2130001000
2019-01US1120002000
2019-01DE1120002000

1. Monthly Transactions I LeetCode Solution MySQL

select 
  date_format(trans_date, '%Y-%m') as month, 
  country, 
  count(*) as trans_count, 
  sum(
    if(state = 'approved', 1, 0)
  ) as approved_count, 
  sum(amount) as trans_total_amount, 
  sum(
    if(state = 'approved', amount, 0)
  ) as approved_total_amount 
from 
  Transactions 
group by 
  date_format(trans_date, '%Y-%m'), 
  country;
Scroll to Top