๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ ๋ฌธ์
https://leetcode.com/problems/monthly-transactions-i/description/
Table : Transactions
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.
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
๊ฐ ์๊ณผ ๊ตญ๊ฐ๋ณ ๊ฑฐ๋ ๊ฑด์์ ์ด์ก, ์น์ธ๋ ๊ฑฐ๋ ๊ฑด์์ ์ด์ก์ ๊ตฌํด์ผ ํ๋ค.
โ ์๊ณผ ๊ตญ๊ฐ์ ๋ํ ๊ทธ๋ฃนํ์ด ํ์ํ๊ณ - group by์ ์ ์ ์ฉ
- ๊ธฐ์กด ํ ์ด๋ธ์ ๋ ์ง ๋ฐ์ดํฐ์ธ trans_date๋ ๋ ์ง๊ฐ ์ผ๊น์ง ๋์์์ด date_format() ํจ์๋ฅผ ์ฌ์ฉํด์ ์๊น์ง ์ ์ฒ๋ฆฌ
โก ์ ์ฒด ๊ฑฐ๋ ๊ฑด์์ ์ด์ก์ โ ๊ทธ๋ฃนํ ์กฐ๊ฑด์ ๋ฐ๋ฅธ ์ง๊ณ๊ฐ ๋๋๋ก COUNT, SUM ํจ์๋ฅผ ์ฌ์ฉํ๋ค.
โข ์น์ธ๋ ๊ฑฐ๋๊ฑด์(approved_count)๋ state ์ปฌ๋ผ๊ฐ์ด 'approved'์ธ ๊ฒฝ์ฐ์ ํํด์ ๊ฐ์ ์ง๊ณํด์ผํ๋ฏ๋ก CASE๋ฌธ์ ์ฌ์ฉํด์ 'approved'์ธ ๊ฒฝ์ฐ์ 1, ์๋ ๊ฒฝ์ฐ 0์ผ๋ก ๊ตฌ๋ถํ๊ณ ํฉ์ ๊ตฌํ๋ค.
โฃ ์น์ธ๋ ๊ฑฐ๋์ ์ด์ก(approved_total_amount) ๋ํ CASE๋ฌธ์ ์ฌ์ฉํ๋, ํด๋นํ๋ ๊ธ์ก๊ฐ์ ํฉ์ ๊ตฌํ๋ฉด ๋๋ฏ๋ก
์กฐ๊ฑด ์ถฉ์กฑ์ ์ปฌ๋ผ๊ฐ์ธ 'amount' ๊ทธ๋๋ก ๋ฏธ์ถฉ์กฑ์ 0์ผ๋ก CASE๋ฌธ์ ์์ฑํ๋ค.
SELECT DATE_FORMAT(trans_date, '%Y-%m') AS month,
country,
COUNT(*) 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 1, 2
'Growth ๐ณ > Practice ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
1907. Count Salary Categories (0) | 2023.09.24 |
---|---|
[Leet code] 1341. Movie Rating (1) | 2023.09.22 |
[Leet code] 1174. Immediate Food Delivery II (0) | 2023.09.15 |
[Leet code] 1141. User Activity for the Past 30 Days IEasy474634 (0) | 2023.09.13 |
[Leet code] 610. Triangle Judgement (0) | 2023.09.13 |