키워드를 이용한 특수한 컬럼 조회하기
: group by, having
● subscriptions 테이블 생성
| Table Name : subscriptions - id : 구독자 고유 ID (프라이머리 키, 자동 증가) - user_name : 구독자명 (문자열, 최대 50자) - plan_name : 플랜명 (문자열, 최대 50자) - start_date : 구독 시작일 (날짜) - end_date : 구독 종료일 (날짜) - status : 구독 상태 (문자열, 최대 20자) - price : 구독 요금 (정수형) |
● subscriptions 테이블에 데이터 추가
| INSERT INTO subscriptions (user_name, plan_name, start_date, end_date, status, price) VALUES ('김철수', 'Premium', '2023-01-01', '2023-12-31', 'Active', 12000), ('이영희', 'Basic', '2023-06-01', '2023-11-30', 'Expired', 6000), ('박준혁', 'Standard', '2023-07-01', '2023-12-31', 'Active', 9000), ('최수진', 'Premium', '2023-01-01', '2023-12-31', 'Active', 12000), ('정우진', 'Basic', '2023-02-01', '2023-07-31', 'Expired', 6000), ('한지수', 'Standard', '2023-03-01', '2023-08-31', 'Expired', 9000), ('김지훈', 'Premium', '2023-04-01', '2023-12-31', 'Active', 12000), ('이민영', 'Basic', '2023-05-01', '2023-10-31', 'Expired', 6000), ('장서현', 'Standard', '2023-06-01', '2023-12-31', 'Active', 9000), ('박다연', 'Premium', '2023-01-01', '2023-12-31', 'Active', 12000); |
● 실습문제
1. 플랜별로 구독자의 수를 조회
|
select plan_name, count(*) as cnt
from subscriptions group by plan_name; |

2. 구독 상태별로 총 구독 요금을 계산
|
select status, sum(price) as total_price
from subscriptions group by status; |

3. 플랜별 평균 구독 요금을 계산
|
select plan_name, avg(price) as avg_price
from subscriptions group by plan_name; |

4. 구독자가 2명 이상인 플랜의 이름과 구독자 수를 조회
|
select plan_name, count(id) as cnt_user
from subscriptions group by plan_name HAVING cnt_user >= 2; |

5. 총 구독 요금이 30000 이상인 구독 상태를 조회
|
select status, sum(price) as sum_price
from subscriptions group by status HAVING sum_price >= 30000; |

6. 플랜별로 2023년 6월 1일 이후에 시작된 구독자 수를 조회하되,
구독자가 2명 이상인 플랜만 조회하고,
구독자가 많은 순서로 정렬
|
select plan_name, count(id) as cnt_user
from subscriptions where start_date >= '2023-06-01' group by plan_name HAVING cnt_user >= 2 order by cnt_user desc; |

7. 상태가 Active인 구독자의 플랜별 총 구독 요금을 계산하되,
총 구독 요금이 20000 이상인 플랜만 조회하고,
총 구독 요금이 높은 순서대로 정렬
|
select plan_name, sum(price) as sum_price
from subscriptions where status = 'Active' group by plan_name HAVING sum_price >= 20000 order by sum_price desc; |

.
.
.

'Database > MySQL 실습' 카테고리의 다른 글
| [DBeaver] MySQL 실습 - 여러테이블 조인(join)하기 실습 (0) | 2025.02.13 |
|---|---|
| [DBeaver] MySQL 실습 - 시간처리 실습 (2) | 2025.02.02 |
| [DBeaver] MySQL 실습 - CRUD 및 문자열 처리 실습 2 (0) | 2025.01.14 |
| [DBeaver] MySQL 실습 - CRUD 및 문자열 처리 실습 (0) | 2025.01.12 |
| [DBeaver] MySQL 실습 - CRUD 실습 (데이터 추가, 조회, 수정, 삭제) (2) | 2025.01.12 |