코딩테스트/SQL 코드카타
MySQL 해커랭크 | Challenges (WHERE절과 HAVING절 차이)
ANNASENA
2024. 8. 23. 08:00
728x90
문제
https://www.hackerrank.com/challenges/challenges/problem?isFullScreen=true
Challenges | HackerRank
Print the total number of challenges created by hackers.
www.hackerrank.com
- Write a query to print the hacker_id, name, and the total number of challenges.
- Sort your results by the total number of challenges in descending order.
- If more than one student created the same number of challenges, then sort the result by hacker_id.
- If more than one student created the same number of challenges and the count is less than the maximum number of challenges created, then exclude those students from the result.
# 문제 해석
해커 아이디, 이름, 총 도전횟수 조회하는 쿼리 만들기
- 총 도전 횟수 내림차순이 기본
- 총 도전 횟수가 같은 학생이 있는 경우, 해커 아이디로 정렬하기
- 총 도전 횟수가 같은데, 그 횟수가 최고 도전 횟수보다 적다면 제외시키기
테이블
Hackers 테이블 | Challenges 테이블 |
![]() |
![]() |
풀이과정
▶ WHERE절과 HAVING절의 차이점
- WHERE 조건절 : (행 필터링) 그룹화 또는 집계가 발생하기 전에 레코드를 필터링 하는 데에 사용
- 개별 행에 적용되는 조건
- HAVING 조건절 : (그룹 필터링) 그룹화 또는 집계가 발생한 후에 레코드를 필터링 하는 데에 사용
- 그룹화된 결과 집합에 적용되는 조건
https://wansook0316.github.io/cs/database/2020/04/25/where-having-%EC%B0%A8%EC%9D%B4.html
[SQL] where와 having의 차이 | 완숙의 에그머니🍳
Be On My Wave 🌊 | 뚜렷한 목표, 치밀한 계획, 우직한 실천
wansook0316.github.io
https://velog.io/@ljs7463/SQL-having-%EA%B3%BC-where-%EC%B0%A8%EC%9D%B4
SQL having 과 where 차이
먼저 having절과 where절의 유사점은 둘 다 데이터 세트검색을 필터링할때 사용할 수 있다는 점입니다.having 절과 where절의 차ㅣHaving절은 WHERE절과 비슷하지만 그룹 전체 즉, 그룹을 나타내는 결과
velog.io
# 정답
- WITH절을 이용해 가상 테이블 만들기
- 해커 아이디, 이름, 도전 횟수로 이루어진 테이블
- 메인쿼리문에서
- GROUP BY로 해커 아이디와 이름마다 총 도전 횟수 결과가 나와있을 때
- HAVING절로 총 도전 횟수가 겹치지 않는(총 도전 횟수 별 COUNT값이 1인 값들) 총 도전 횟수들
또는 총 도전 횟수가 MAX값인 경우만 조회하도록 필터링
1 2 3 4 5 6 7 8 9 10 11 12 | WITH hj AS( SELECT h.hacker_id, h.name, COUNT(c.challenge_id) challenges_created FROM Hackers h JOIN Challenges c ON h.hacker_id = c.hacker_id GROUP BY 1, 2 ORDER BY 3 DESC, 1 ) SELECT hacker_id, name, challenges_created FROM hj GROUP BY 1,2 HAVING challenges_created IN (SELECT challenges_created FROM hj GROUP BY challenges_created HAVING COUNT(challenges_created)=1) OR challenges_created= (SELECT MAX(challenges_created) FROM hj) | cs |
728x90