[๋ฆฌํธ์ฝ๋] 1193. Monthly Transactions I - group by ์ปฌ๋ผ์์ null, count(*), sum(case๋ฌธ)โ
# ๋ฌธ์
https://leetcode.com/problems/monthly-transactions-i/description/
# ๋ฌธ์ ์ค๋ช
# ํท๊ฐ๋ ธ๋ ๋ถ๋ถ๋ค
1. group by ์ปฌ๋ผ1, ์ปฌ๋ผ2๋ก ๋ฌถ์ํ count()๋ฅผ ํ ๋ count(*)๋ฅผ ํ๋ฉด null๊ฐ๊น์ง ์ธ๋ฒ๋ฆฌ๋๊ฒ ์๋๊น?
Q) group by ์ปฌ๋ผ1, ์ปฌ๋ผ2๋ฅผ ํ ๋ ์ปฌ๋ผ1์ด๋ ์ปฌ๋ผ2์ null๊ฐ์ด ๋ค์ด๊ฐ ์ ์์๊น? ๋ง์ฝ ๋ค์ด๊ฐ๋ค๋ฉด ์ด๋ป๊ฒ ํด์ผ ํ๋?
2. with๋ฌธ์ผ๋ก ๋ฐ๋ก ํ ์ด๋ธ์ ๋ง๋ค์ง ์๊ณ ์กฐ๊ฑด์ ๋ฐ๋ผ์ sum()์ ํ ์๋ ์์๊น?
# ํต์ฌ ๊ฐ๋
1. GROUP BY๋ NULL ๊ฐ๋ ๊ทธ๋ฃนํํฉ๋๋ค.
๋ฐ๋ผ์ COUNT(*)๋ฅผ ์ฌ์ฉํ๋ฉด ๊ทธ๋ฃน์ ์ ์ฒด ํ ์๋ฅผ ์ ํํ๊ฒ ์ ์ ์์ต๋๋ค.
๋ฐ๋ฉด์ ํน์ ์ปฌ๋ผ์ ๋ํด NULL ๊ฐ์ ์ ์ธํ๊ณ ๊ฐ์๋ฅผ ์ธ๊ณ ์ ํ๋ค๋ฉด, COUNT(column1) ๋๋ COUNT(column2)๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค
๊ทธ๋ฆฌ๊ณ ์ด๋ฒ ๋ฌธ์ ์ ๊ฐ์ด ๊ฐ์๋ฅผ ์ธ๋ ๊ฒฝ์ฐ count(*)๋ฅผ ํด๋ ๋ฌด๋ฐฉํ๋ค
๊ทธ๋ฌ๋ count(*)๊ณผ count(์ปฌ๋ผ)์ ๋ค๋ฅด๋ค
๋ง์ฝ group by ์ปฌ๋ผ1, ์ปฌ๋ผ2์ค null๊ฐ์ด ๋ค์ด๊ฐ ๊ทธ๋ฃน์ ํํฐ๋งํ๊ณ ์ถ๋ค๋ฉด count(์ปฌ๋ผ)์ ํ๋ฉด ๋๋ค
๋ค์๊ณผ ๊ฐ์ ๋ฐ์ดํฐ๊ฐ ์๋ค๊ณ ๊ฐ์ ํ์
count(*) - ๋ค์ ์ฟผ๋ฆฌ๋ฅผ ์คํํ์๋
๊ฒฐ๊ณผ๋ ๋ค์๊ณผ ๊ฐ๋ค
count(์ปฌ๋ผ) - ๋ค์ ์ฟผ๋ฆฌ๋ฅผ ์ํํ์๋ country๊ฐ null์ธ ๊ทธ๋ฃน์ ๋์ค์ง ์๊ฒ ๋๋ค
2. SUM(CASE WHEN ์กฐ๊ฑด THEN ๊ฐ ELSE ์๋๋๊ฐ end)
๋จผ๊ฐ ํ์ด์ฌ์ ์ผํญ์ฐ์ฐ์
๊ฐ if ์กฐ๊ฑด else ์๋๋๊ฐ
๊ณผ ๋น์ทํ ๋๋์ด๋ค
# ๋ด๊ฐ ์ด ์ ๋ต์ฝ๋
with new_table as (
select date_format(trans_date, '%Y-%m') as month,
country,
case when state = 'approved' then 1
else 0 end as state_cnt,
amount
from Transactions
)
select month,
country,
count(*) as trans_count,
sum(state_cnt) as approved_count,
sum(amount) as trans_total_amount,
sum(state_cnt * amount) as approved_total_amount
from new_table
group by month, country
# ๋ค๋ฅธ ์ฌ๋์ด ์ด ์ ๋ต์ฝ๋
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 month, country