-
[2주차] SQL 2주차카테고리 없음 2022. 12. 21. 11:39
스파르타코딩클럽 내일배움단 '엑셀보다 쉬운 SQL'
2주차 주요 내용: 범주의 통계 group by, 정렬 order by, 별칭 as (alias)
[group by]
동일한 범주를 갖는 데이터를 하나로 묶어서 범주별 통계
select payment_method, count(*) from orders group by payment_method;범주별로 묶어서 개수를 알 수 있다!
select * from orders 를 먼저 쓰고 group by로 범주 설정한 후 봐야 할 데이터를 생각한 다음에
select payment_method, count(*) from orders 로 수정
> 이게 더 이해하고 실행하기 쉬움
- 최소(min)
select course_id, min(likes) from checkins group by course_id;select 범주가 담긴 필드명, min(최솟값을 알고 싶은 필드명) from 테이블명 group by 범주가 담긴 필드명;- 최대(max)
select course_id, max(likes) from checkins group by course_id;select 범주가 담긴 필드명, max(최댓값을 알고 싶은 필드명) from 테이블명 group by 범주가 담긴 필드명;- 평균(avg)
select course_id, avg(likes) from checkins group by course_id;select 범주가 담긴 필드명, avg(평균값을 알고 싶은 필드명) from 테이블명 group by 범주가 담긴 필드명;- 합계(sum)
select course_id, sum(likes) from checkins group by course_id;select 범주가 담긴 필드명, sum(합계를 알고 싶은 필드명) from 테이블명 group by 범주가 담긴 필드명;- where 절과 함께 쓰려면?
select payment_method, count(*) from orders where course_title = '웹개발 종합반' group by payment_method;[order by]
- 오름차순
select name, count(*) from users group by name order by count(*);- 내림차순 (desc)
select name, count(*) from users group by name order by count(*) desc;- group by 를 안쓰고도 사용 가능!
select * from checkins order by likes;[alias 별칭]
데이터가 너무 방대할 때, 같은 필드명이 많을 때
- 방법1
select * from orders o where o.course_title = '앱개발 종합반'-방법2
select payment_method, count(*) as cnt from orders o where o.course_title = '앱개발 종합반' group by payment_method