GROUP BY/HAVING (+해커랭크 예제)
https://www.w3schools.com/sql/sql_groupby.asp
Demo Database
- GROUP BY
특정 칼럼을 기준으로 모아보고 싶을 때 사용, python에서 pandas 라이브러리를 활용하여 그룹화하는거랑 마찬가지
1. SupplierID를 기준으로 평균 가격을 출력하자
SELECT supplierID
, AVG(Price)
FROM Products
GROUP BY supplierID
이때, GROUPBY에 있는 칼럼명은 항상 SELECT에도 들어가 있어야함
(→ 여기서 18번 SupplierID의 평균 공급 가격이 상대적으로 높게 나오니까, 얘를 유의해서 데이터를 살펴볼 수 있음)
2. 추가로 SupplierID가 1인 사람의 CategoryID도 같이 보고 싶으면, 얘도 기준으로 세워서
SELECT supplierID
, categoryid
, AVG(Price)
FROM Products
GROUP BY supplierID, categoryid
-- MySQL은 숫자도 지원, selecet에 있는 1번째, 2번째 칼럼을 기준으로 그룹화하라는 뜻
이렇게 SupplierID가 1인 사람이 categoryID는 무엇 무엇을 갖고있는지 볼 수 있음
3. 여기서 평균 가격이 높은 순, 낮은 순대로 보고싶다면 ORDER BY 쓰면 됌
SELECT supplierID
, categoryID
, AVG(Price)
FROM Products
GROUP BY SupplierID, categoryID
ORDER BY AVG(price) DESC -- 내림차순
- HAVING
GROUP BY를 한 후 조건을 걸고 싶을 때 사용
일반적으로, GROUP BY와 WHERE문을 같이 쓰고 싶으면 WHERE문이 먼저 와야함
1. GROUP BY의 결과물 중에 100불 이상인 데이터를 가져오자
>> avg(price)를 기준으로 필터링을 걸기
SELECT supplierID
, categoryID
, AVG(Price)
FROM Products
GROUP BY supplierID, categoryID
HAVING AVG(Price) >= 100
2. 출력 결과에 새로운 칼럼명 지정하고, HAVING에서 새로운 칼럼명으로 불러오기
SELECT supplierID
, categoryID
, AVG(Price) AS avg_price
FROM Products
GROUP BY supplierID, categoryID
HAVING avg_price >= 100
- 해커랭크 예제 연습
https://www.hackerrank.com/challenges/earnings-of-employees/problem?isFullScreen=true
Top Earners | HackerRank
Find the maximum amount of money earned by any employee, as well as the number of top earners (people who have earned this amount).
www.hackerrank.com
문제 설명
We define an employee's total earnings to be their monthly 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 space-separated integers.
Input Format
The Employee table containing employee data for a company is described as follows:

where employee_id is an employee's ID number, name is their name, months is the total number of months they've been working for the company, and salary is the their monthly salary.
Sample Input

Sample Output
69952 1
Explanation
The table and earnings data is depicted in the following diagram:

The maximum earnings value is 69952. The only employee with earnings = 69952 is Kimberly, so we print the maximum earnings value (69952) and a count of the number of employees who have earned $69952 (which is 1) as two space-separated values.
풀이 접근
1. 월급*개월 곱한 칼럼을 earnings로 새로 지정 >> 사칙연산, as 사용
2. 각 earnings별로 몇 명이 그만큼 벌었는지 카운트 >> group by로 그룹화, count 사용
3. earnings 중에 가장 큰 값 한 개 가져오기 >> order by, limit 사용
SELECT salary * months AS earnings
, COUNT(*)
FROM employee
GROUP BY earnings
ORDER BY earnings DESC
LIMIT 1
>> 처음 풀 때 시간 오래 걸려서 다른 문제로 group by, having 복습 필수