SQL 기초 2 _ group by, order by

백지연·2022년 11월 20일
0

3. group by

group by 란?

동일한 범주를 갖는 데이터를 하나로 묶어서, 범주별(category) 통계를 내주는 것

# 성씨별 회원수 파악하기
select name, count(*) from users
group by name;

group by 로 통계내기

1) 동일 범주의 개수

select 범주별로 세어주고 싶은 필드명, count(*) from 테이블명
group by 범주별로 세어주고 싶은 필드명;

2) 동일 범주의 최솟값

select 범주가 담긴 필드명, min(최솟값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;

3) 동일 범주의 최댓값

select 범주가 담긴 필드명, max(최댓값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;

4) 동일 범주의 평균

select 범주가 담긴 필드명, avg(평균값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;

5) 동일 범주의 합계

select 범주가 담긴 필드명, sum(합계를 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;

4. order by

order by 란?

깔끔한 정렬 제공

1) 오름차순

select name, count(*) from users
group by name
order by count(*);

2) 내림차순

select name, count(*) from users
group by name
order by count(*);

where + order by + group by

# 웹개발 종합반의 결제수단별 주문건수 세어보기
select payment_method, count(*) from orders
where course_title = "웹개발 종합반"
group by payment_method;
# 네이버 이메일을 사용하여 앱개발 종합반을 신청한 주문의 결제수단별 주문건수 세어보기
select payment_method, count(*) from orders
where email like '%naver.com' and course_title = '앱개발 종합반'
group by payment_method
profile
문어발 공부

0개의 댓글