
코린이의 SQL 2주차
: 동일한 범주의 데이터를 묶어주어, 통계를 내주기
문제 : 성씨별로 몇 명이 회원이 있는지 구하기
SELECT * FROM users
group by name
SELECT name, COUNT(*) FROM users
group by name
쿼리가 실행되는 순서: from → group by → select
주차별 '오늘의 다짐' 개수 구하기
> 테이블로 값만 카운트 보여주기
SELECT week, COUNT(*) FROM checkins
group by week
> 조건의 해당 값 카운트 모두 보여주기
SELECT * FROM checkins
where week =1
select week, min(likes) from checkins
group by week
select week, max(likes) from checkins
group by week
select week, avg(likes) from checkins
group by week
+참고
소수점 반올림 : round(avg(평균값을 알고 싶은 필드명), 보여주고자 하는 소수점의 자리수)
select week, sum(likes) from checkins
group by week
'신' 씨를 가진 데이터만 불러와서 개수 > group by를 사용해서 '신'씨를 가진 데이터가 몇 개인지
SELECT name, COUNT(*) FROM users
WHERE name = '신**'
GROUP by name
쿼리가 실행되는 순서: from → where → select → group by
퀴즈
- 앱개발 종합반의 결제수단별 주문건수 세어보기
SELECT payment_method, count(*) FROM orders group by payment_method2. Gmail 을 사용하는 성씨별 회원수 세어보기SELECT name, count(*) FROM users
where email LIKE '%@gmail.com'
group by name3. course_id별 '오늘의 다짐'에 달린 평균 like 개수 구해보기SELECT course_id, ROUND(avg(likes),1) FROM checkins
group by course_id
: 깔끔한 정렬이 필요할때 사용
SELECT * FROM users
group by name
SELECT name, COUNT(*) FROM users
group by name
아무것도 적지 않으면 기본적으로 오름차순
SELECT name, COUNT(*) FROM users
group by name
order by count(*)
쿼리가 실행되는 순서: from → group by → select → order by
step1
step2
영단어 descending의 약자
SELECT name, COUNT(*) FROM users
group by name
order by count(*) desc
select * from users
order by email
select * from users
order by name;
select * from users
order by created_at desc;
Where절로 조건이 하나 추가되고, 그 이후에 Group by, Order by가 실행되는 것!
select*from oreders
select*from oreders
where course_title= '웹개발 종합반'
select*from oreders
where course_title= '웹개발 종합반'
group by payment_method
select payment_method, count(*) from orders
where course_title= '웹개발 종합반'
group by payment_method
select payment_method, count(*) from orders
where course_title= '웹개발 종합반'
group by payment_method
order by count(*)
: 별칭붙여주기 (길어지는 쿼리를 짧게)
orders 테이블을 o > 테이블 o 안에 코스타이틀(o.course_title)
count(*) 를 as cnt > cnt 필드명으로 출력
SELECT payment_method, count(*) as cnt FROM orders o
where o.course_title ='앱개발 종합반'
group by payment_method