데이터베이스(DB)/SQL
[엑셀보다 쉬운 SQL] 2주차 + 기본 sql 문법
Jye_647
2023. 5. 8. 15:40
Group by
group by → 묶어주기
select name, count(*) from users group by name
users를 name별로 묶고, name과 name별로 묶은 수 보기
Group by 기능들
개수 구하기 | count select week, count(*) from checkins group by week week별로 묶은 week의 개수 구하기 |
최소값 구하기 | min(필드명) |
최대값 구하기 | max(필드명) |
평균값 구하기 | avg(필드명) select week, round(avg(likes),2) from checkins group by week round(avg(필드명), 소수점자리) |
합계 구하기 | sum(필드명) |
Order by
order by → 정렬
select name, count(*) from users group by name order by count(*)
users를 name 별로 묶고, name과 name 별로 묶은 수를 보는데 count별로 정렬해서 보여줘
*기본 오름차순(asc; ascending), 내림차순을 원한다면 desc(descending)를 붙여준다.
Alias (별칭 기능)
select * from orders where course_title = '앱개발 종합반'
위처럼 데이터가 점점 많아질수록 course_title이 여러개 일 수 있다.
이럴 때 어떤 테이블의 course_title인지 쉽게 알기 위해 별칭을 만들어준다.
↓
select * from orders o where o.course_title = '앱개발 종합반'
보통 한글자에서 두 글자 정도의 alias를 생성한다.
예시) count(*)에 별칭을 부여
select payment_method, count(*) from orders o
where o.course_title= '앱개발 종합반'
group by payment_method
↓
select payment_method, count(*) as cnt from orders o
where o.course_title= '앱개발 종합반'
group by payment_method