Everyday Dev System

엑셀보다 쉬운 SQL - 2일차 본문

내배캠 초기 학습/엑셀보다 쉬운, SQL

엑셀보다 쉬운 SQL - 2일차

chaeyoung- 2023. 5. 3. 12:38

11:50 AM -12:35 AM

order by , group by , round , alias

 

** 게시판 DB에서 Created at / Updated at  필드 통상적으로 현업에서 많이 사용됨.

Created at : 게시글이 처음 작성된 시기 

Updated at : 게시글이 가장 최근에 수정된 시기

 

 

동일한 데이터를 묶어주는 Group by 

통계 : 최대 / 최소 / 평균 / 갯수

//성씨 별로 몇명이 있는지 조회

select name,count(*) from users

group by name

 

//네이버 이메일을 쓰는 사람들 중에서 성씨 별로 몇명이 있는지 조회

select name,count(*) from users u where email like '%naver%' group by name

/*검증 쿼리문

select * from users where name like '임**' and email like '%naver%' */

select * from checkins

 

 

//주차별로 오늘의 다짐 갯수 구하기

select week, count(*) from checkins group by week

/*검증 쿼리문

select * from checkins where week=3 */

 

//주차별로 like의 최소값, 최대값, 평균값, 합계

select week, min(likes) from checkins c group by week

select week, max(likes) from checkins c group by week

select week, avg(likes) from checkins c group by week

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

select week, sum(likes) from checkins c group by week

 

 

 

 

 

 

 

깔끔하게 데이터를 정렬해주는 Order by

//정렬은 마지막에 실행

//기본 생략 혹은 asc 오름차순, desc 내림차순

select name, count(*) from users

group by name

order by count(*) desc

 

//좋아요 많은 정렬

select * from checkins c

order by likes desc

 

 

그룹, 정렬 where절과 함께 사용하기

// 웹개발 종합반의 결제수단별 주문건수 오름차순으로 조회

select payment_method, count(*) from orders

where course_title = '웹개발 종합반'

group by payment_method

order by count(*)

 

그룹과 정렬 함께 사용하기

// 문자열 기준 정렬하기

select * from users u

order by email desc

 

select * from users u

order by created_at desc

 

//앱개발 종합반의 결제수단별 주문건수 세기

select payment_method, count(*) from orders o

where course_title = '앱개발 종합반'

group by payment_method

 

//gmail을 사용하는 성씨별 회원수

select name,count(*) from users u

where email like '%gmail.com%'

group by name

 

//course_id별 오늘의 다짐에 달린 평균 like 갯수

select course_id , round(avg(likes),1) from checkins c

group by course_id

 

소수점 반올림 - round

round(avg(likes),2)

 

별칭 Alias

// 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

 

Homeworks

//네이버 이메일을 사용해서 앱개발 종합반을 신청한 주문의 결제수단별 주문건수 세기

select payment_method, count(*) as CNT from orders o

where email LIKE '%naver.com%' and course_title = '앱개발 종합반'

group by payment_method

 

/*검증 쿼리문

select * from orders o

where email LIKE '%naver.com%' and course_title = '앱개발 종합반'

order by payment_method */

 

 

** 게시판 DB에서 Created at / Updated at  필드 통상적으로 현업에서 많이 사용됨.

Created at : 게시글이 처음 작성된 시기 

Updated at : 게시글이 가장 최근에 수정된 시기