범주의 통계를 내주는 Group by
결과를 정렬해주는 Order by
예시) select name, count(*) from users group by name
쿼리가 실행되는 순서 : from → group by → select
- from users: users 테이블 데이터 전체를 가져옵니다.
- group by name: users 테이블 데이터에서 같은 name을 갖는 데이터를 합쳐줍니다.
- select name, count(*): name에 따라 합쳐진 데이터가 각각 몇 개가 합쳐진 것인지 세어줍니다.
예시) select payment_method, count(*) from orders
where course_title = "웹개발 종합반"
group by payment_method
쿼리가 실행되는 순서: from → where → group by → select
- from orders: users 테이블 데이터 전체를 가져옵니다.
- where course_title = "웹개발 종합반": 웹개발 종합반 데이터만 남겨줍니다.
- group by payment_method: 같은 payment_method을 갖는 데이터를 합쳐줍니다.
- select payment_method, count(*): payment_method에 따라 합쳐진 데이터가 각각 몇 개가 합쳐진 것인지 세어줍니다.
- 예) CARD, CARD, kakaopay 이렇게 데이터가 있었다면, CARD는 2개, kakaopay는 1개겠죠!
예시) select name, count(*) from users
group by name
order by count(*);
쿼리가 실행되는 순서: from → group by → select → order by
- from users: users 테이블 데이터 전체를 가져옵니다.
- group by name: users 테이블 데이터에서 같은 name을 갖는 데이터를 합쳐줍니다.
- select name, count(*): name에 따라 합쳐진 데이터가 각각 몇 개가 합쳐진 것인지 세어줍니다.
- 예) 이**, 이**, 김**, 김**, 박** 이렇게 데이터가 있었다면, 이는 2개, 김은 2개, 박**은 1개겠죠!
- order by count(*): 합쳐진 데이터의 개수에 따라 오름차순으로 정렬해줍니다.
이외 유용한 문법
select payment_method, count(*) as cnt from orders o
where o.course_title = '앱개발 종합반'
group by payment_method
댓글 영역