How To Solve LeetCode 1193
Source: Dev.to
Problem Description
The table Transactions has the following columns:
id(primary key)countrystate(enumeration:'approved'or'declined')amounttrans_date
We need to return, for each month‑year and country, the following aggregates (order does not matter):
month– formatted asYYYY-MMtrans_count– total number of transactionsapproved_count– number of approved transactionstrans_total_amount– sum of all transaction amountsapproved_total_amount– sum of amounts for approved transactions
Approach
- Grouping – Group rows by the month‑year derived from
trans_dateand bycountry. - Aggregations –
COUNT(id)gives the total transaction count.SUM(amount)gives the total transaction amount.- For the approved‑only metrics, use
CASEexpressions insideSUM:- Return
1(oramount) whenstate = 'approved', otherwise0.
- Return
- Month formatting – In PostgreSQL,
TO_CHAR(trans_date, 'YYYY-MM')converts the date to the requiredYYYY-MMstring.
SQL Query
SELECT
TO_CHAR(trans_date, 'YYYY-MM') AS month,
country AS country,
COUNT(id) AS trans_count,
SUM(
CASE
WHEN "state" = 'approved' THEN 1
ELSE 0
END
) AS approved_count,
SUM(amount) AS trans_total_amount,
SUM(
CASE
WHEN "state" = 'approved' THEN amount
ELSE 0
END
) AS approved_total_amount
FROM Transactions
GROUP BY TO_CHAR(trans_date, 'YYYY-MM'), country;