SQL 2주차 수업내용이다.
2주차에는 SQL에서 그룹으로 묶어서 보기편하게 표기하고,통계를 구할 수도 있으며 그것을 order by를 이용해 정렬 하는 법을 배웠다.
또, 실무에서 진짜 사람들이 궁금해하는 데이터인 최소, 최대, 평균값 등을 알아내는 방법도 공부했다.
Group by
group by를 사용하면 데이터를 종류별로 빠르게 나누고 표기할 수 있다.
select name, count(*) from users
group by name;
#성씨별 회원수를 성씨별로 가져와줘.
이렇게 group by를 이용하면 같은 중복되는 값끼리 묶을 수 있다.
따라서 위와같이 빠르게 한 그룹에 몇명이 있는지 같은 데이터를 구할 수 있다.
ex)이씨는 85명 이구나!
코드실행 순서★★★
group by를 알았으니 코드가 실행되는 순서를 알아야한다.
코드는 from -> group by -> select 순서로 실행된다.
그러니까
from user : 테이블 전체의 데이터를 가져온다. ->
group by name : name 데이터에 같은 name을 갖는 데이터를 합쳐준다.->
select name, count(*) : name에 각각 몇개의 데이터가 합쳐진지 세어준다.
와 같은 순서로 실행된다.
참고로 where까지 추가된 코드라면 from -> where -> group by -> select순으로 실행된다.
Order by
order by는 구한 데이터들을 오름차순이나 내림차순으로 정렬할 때 사용된다.
select * from checkins
order by likes desc;
#checkins테이블의 모든 데이터에서 likes를 내림차순으로 정렬해줘
위와같이 desc를 쓰면 내림차순으로 정렬된다.
오름차순으로 정렬하고 싶을 시 asc를 쓰면 되지만 아무것도 쓰지않아도 오름차순으로 정렬된다.
order by가 있는 코드의 경우에는 from → group by → select → order by순으로 실행된다.
Alios
코드가 점점 길어져서 알아보기 힘든경우를 생각해 SQL은 Alios라고하는 별칭 기능을 지원한다.
select * from orders o
where o.course_title = '앱개발 종합반'
#orders 뒤에 o는 orders를 가리키는 별칭
위와같이 별칭으로 사용할 수 있다.
출력된 필드에 별칭을 붙이는 것도 가능하다.
select payment_method, count(*) as cnt from orders o
where o.course_title = '앱개발 종합반'
group by payment_method
위와 같이 count 대신 cnt라는 별칭이 사용되었다.
최대, 최소, 평균값 구하기
최대 최소 평균값은 각각 영어의 약자 max, min, avg를 사용한다.
max
select max(likes)from checkins
#checkins 테이블에 likes데이터의 최댓 값을 줘
min
select min(likes)from checkins
#checkins테이블의 likes데이터의 최솟 값을 줘
avg
select avg(likes)from checkins
#checkins테이블의 likes데이터의 평균 값을 구해줘
하지만 평균 값을 구하면 소수점 아래까지 모두 출력된다.
그럴때는 round를 이용해 반올림 해줄 수 있다.
select round(avg(likes),1) from checkins
#round(avg(데이터),반올림하여 표기할 소수점 아래 숫자)
위와같이 사용할 수 있다.
아래는 결과 값!