96번 - Monthly Transaction (총량 + 특정 조건 집계하기)
- 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.The query result format is in the following example.
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 | +----------+---------+-------------+----------------+--------------------+-----------------------+
▶️ 내 코드 (오답)
#월별, 나라 별 거래량, 총 거래량, 승인된 거래수, 승인된 거래량 조회
select date_format(trans_date, '%Y-%m') as month,
country,
count(id) trans_count,
if(state='approved', count(id), null) as approved_count,
sum(amount) trans_total_amount,
if(state='approved', sum(amount), null) as approved_total_amount
from transactions
group by 1, 2
결과
- approved_count 2가 아닌 1
- approved_total_amount 3000이 아닌 2000
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
| ------- | ------- | ----------- | -------------- | ------------------ | --------------------- |
| 2018-12 | US | 2 | 2 | 3000 | 3000 |
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |...
❗️어려웠던 점
: 하나의 테이블에서 특정 조건을 준 값을 집계하는 동시에 총량을 집계하는 것
⇒ case when문을 사용해 조건을 주고 그 바깥에 집계 함수를 써줌
SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count,
SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) As approved_total_amount
▶️ 정답 쿼리
select date_format(trans_date, '%Y-%m') as month,
country,
count(id) trans_count,
sum(case when state='approved' then 1 else 0 end) as approved_count,
sum(amount) trans_total_amount,
sum(case when state='approved' then amount else 0 end) as approved_total_amount
from transactions
group by 1, 2
'SQL > 예제로 익히는 SQL 함수' 카테고리의 다른 글
[MySQL] DATEDIFF, TIMESTAMPDIFF, INTERVAL (0) | 2024.05.30 |
---|---|
[컬럼 만들기] 회원가입 각 단계 전환율 구하기 - SQL Challenge 세션 과제2 (0) | 2024.05.30 |
[SQL] 이동평균을 통해 매출 추이 살펴보기 (1) | 2024.05.23 |
JOIN | ON절과 WHERE절의 차이점 (0) | 2024.05.13 |
MOD | SQL에서 나머지와 몫 (짝수, 홀수) (0) | 2024.05.08 |