[강의] 스파르타 코딩클럽 SQL 2주차

lzlkolo·2022년 12월 27일
0

범주를 묶어주는 Group by
깔끔하게 데이터를 정렬해주는 Order by

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

성씨별로 묶은 데이터를 카운트해서 가져와라

출력화면

group by

  1. 동일한 범주의 개수 구하기
  • 주차별 '오늘의 다짐' 개수 구하기
select week, count(*) from checkins
group by week

  • where문으로 결과가 동일한지 검증
select * from checkins
where week = 1
  1. 동일한 범주의 최소값 구하기
  • 주차별 '오늘의 다짐'의 좋아요 최소값 구하기
select week, min(likes) from checkins
group by week

  1. 동일한 범주의 최대값 구하기
  • 주차별 '오늘의 다짐'의 좋아요 최대값 구하기
select week, max(likes) from checkins
group by week

  1. 동일한 범주의 평균값 구하기
  • 주차별 '오늘의 다짐'의 좋아요 평균값 구하기
select week, avg(likes) from checkins
group by week

round로 소수점 2자리까지 나오게 할 수 있음

select week, round(avg(likes), 2) from checkins
group by week

  1. 동일한 범주의 합계 구하기
  • 주차별 '오늘의 다짐'의 좋아요 합계 구하기
select week, sum(likes) from checkins
group by week

order by

결과 정렬
성씨별로 count한 결과를 count기준으로 정렬

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

order by는 오름차순으로 정렬되는데 내림차순으로 정렬하려면 desc를 붙이면 된다.

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

where문 + group by, order by

웹개발 종합반의 결제수단별 주문건수 세어보기

select payment_method, count(*) from orders
where course_title = '웹개발 종합반'
group by payment_method 

count별 정렬 추가

select payment_method, count(*) from orders
where course_title = '웹개발 종합반'
group by payment_method 
order by count(*) 

show tables로 어떤 테이블이 있는지 볼 수 있다.

Alias

별칭 기능 지원

select * from orders o
where o.course_title = '앱개발 종합반'

구체적으로 쿼리를 지시내릴 수 있음

select payment_method, count(*) as cnt from orders o
where o.course_title = '앱개발 종합반'
group by payment_method 

as

원래 출력 테이블에서 cnt는 count(*)로 출력되는데 as를 붙이면 as뒤의 별칭으로 출력된다.

0개의 댓글

관련 채용 정보