Where 절을 사용해서 수십개의 쿼리를 작성하는 것은 너무 비효율적입니다.
이 문제는 Group by를 사용하여 범주의 통계를 내어 해결 할 수 있습니다.
select name, count(*) from orders
group by name;
select * from users
where name = "신**";
select name, count(*) from users
group by name;
from → group by → select
select * from users;
select * from users
where name = "신**";
select name, count(*) from users
group by name;
select 범주별로 세어주고 싶은 필드명, count(*) from 테이블명
group by 범주별로 세어주고 싶은 필드명;
select 범주가 담긴 필드명, min(최솟값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;
select 범주가 담긴 필드명, max(최댓값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;
select 범주가 담긴 필드명, avg(평균값을 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;
select 범주가 담긴 필드명, sum(합계를 알고 싶은 필드명) from 테이블명
group by 범주가 담긴 필드명;
깔끔한 정렬이 필요할 땐 Order by를 사용하면 한 번에 정렬할 수 있어요.
select name, count(*) from users
group by name;
select name, count(*) from users
group by name
order by count(*);
select name, count(*) from users
group by name
order by count(*) desc;
[꿀팁!] 여기서의 desc는 내림차순을 의미하는 영단어 descending의 약자입니다.
select * from checkins
order by likes desc;
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(*): 합쳐진 데이터의 개수에 따라 오름차순으로 정렬해줍니다.
Where절로 조건이 하나 추가되고, 그 이후에 Group by, Order by가 실행되는 것!
Q) 웹개발 종합반의 결제수단별 주문건수 세어보기
[순서]
1. orders 테이블에서 주문 데이터를 읽어오고
2. 웹개발 종합반 데이터만 남기고
3. 결제수단(범주) 별로 그룹화하고
4. 결제수단별 주문건수를 세어준다!
select payment_method, count(*) from orders
where course_title = "웹개발 종합반"
group by payment_method;
위 쿼리가 실행되는 순서: from → where → group by → select
select * from users
order by email;
select * from users
order by name;
select * from users
order by created_at desc;
select payment_method, count(*) from orders
where course_title = "앱개발 종합반"
group by payment_method;
select name, count(*) from users
where email like '%gmail.com'
group by name;
select course_id, avg(likes) from checkins
group by course_id;
select payment_method, count(*) from orders
where email like '%naver.com' and course_title = '웹개발 종합반'
group by payment_method