GROUP BY
테이블 내에 존재하는 전체의 값에 대한 것이 아닌 특정 그룹의 값에 대해 알고 싶다면, GROUP BY를
이용해 특정 컬럼을 그룹화 할 수 있다.
<exam>
ID | grade | classnum | score |
1 | 1 | 1 | 65 |
2 | 3 | 2 | 89 |
3 | 2 | 3 | 87 |
4 | 2 | 3 | 92 |
5 | 1 | 2 | 77 |
grade별 socre의 평균 구하기
SELECT grade, AVG(score)
FROM exam
GROUP BY grade
- grade = 1 ⇒ (65+77) / 2 = 71
- grade = 2 ⇒ (87+92) / 2 = 89.5
- grade = 3 ⇒ 89 / 1 = 89
- grade가 1인 그룹의 평균, grade가 2인 그룹의 평균, grade가 3인 그룹의 평균
- GROUP BY의 기준인 grade는 반드시 SELECT문에 써줘야 함
grade별, classnum별 score의 평균 구하기
SELECT grade, classnum, AVG(score)
FROM exam
GROUP BY grade, classnum -- grade별, classnum별로 그룹화하기
ORDER BY AVG(score) DESC
- grade=1 classnum=1 ⇒ 65
- grade=1 classnum=2 ⇒ 77
- grade=2 classnum=3 ⇒ (87+92) / 2 = 89.5
- grade=3 classnum=2 ⇒ 89
- 그룹화 기준이 2개일 경우 : GROUP BY 기준1, 기준2
- GROUP BY의 기준인 grade, classnum는 반드시 SELECT문에 써줘야 함
HAVING
GROUP BY로 그룹화된 결과에 조건을 주기 위해서는 WHERE가 아닌 HAVING을 사용해야 한다.
<exam>
ID | grade | classnum | score |
1 | 1 | 1 | 65 |
2 | 3 | 2 | 89 |
3 | 2 | 3 | 87 |
4 | 2 | 3 | 92 |
5 | 1 | 2 | 77 |
grade별, classnum별 score의 평균 중 80이상인 값만 출력하기
SELECT grade
, classnum
, AVG(score) AS avg_score
FROM exam
GROUP BY grade, classnum
HAVING avg_score >= 80
- HAVING절을 이용해 그룹화한 결과값에 조건을 걸어줄 수 있다.
- WHERE절을 사용하면 순서상 GROUP BY절 앞에 위치하므로 그룹화가 진행되기 전에 조건절이 수행된다.
- AS를 이용하여 별명을 붙여줄 수 있다.
<HackerRank 연습문제>
# Top Earners
▶ We define an employee's total earnings to be their monthly salary x months worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as 2 space-separated integers.
- earnings = salary x months
- earnings의 최댓값을 찾아라
- earnings의 최댓값과 이 값을 가진 employee의 수를 출력해라
SELECT salary * months, COUNT(*)
FROM employee
GROUP BY salary * months
ORDER BY salary * months DESC
LIMIT 1
+) AS를 이용해 salary * months의 별칭을 지정해줄 수도 있다.
↘↘↘
[백문이불여일타] 데이터 분석을 위한 중급 SQL
'📖 STUDY > SQL' 카테고리의 다른 글
[SQL] CASE_테이블 피봇 (0) | 2022.03.08 |
---|---|
[SQL] CASE (0) | 2022.03.08 |
[SQL] COUNT, SUM, AVG, MIN, MAX (0) | 2022.03.07 |
[SQL] review_HackerRank (0) | 2022.03.04 |
[SQL] CEIL, FLOOR, ROUND (0) | 2022.03.04 |