[Programmers] 동명 동물 수 찾기 (Success)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
📝 Language: Oracle
1
2
3
4
5
6
|
SELECT NAME, COUNT(NAME)
FROM ANIMAL_INS
GROUP BY NAME
HAVING COUNT(NAME) > 1
ORDER BY NAME;
|
🙂 확인 사항
1. ANIMAL_INS 테이블
2. 두 번 이상 쓰인 이름과
3. 해당 이름이 쓰인 횟수조회
4. 이름이 NULL일 경우, 집계 제외
5. 이름 순 오름차순 조회
⭐ 집계함수는 GROUP BY절에 사용된 컬럼을 사용하지 않아도 됨
- COUNT(*) 가능
- 단, 해당 문제에서는 이름이 NULL일 경우, 집계에서 제외해야하므로 COUNT(NAME)으로 작성
😮 이 외의 풀이
1
2
3
4
5
6
7
8
9
10
|
SELECT DISTINCT A.NAME, B.COUNT
FROM ANIMAL_INS A
JOIN (
SELECT NAME, COUNT(NAME) AS COUNT
FROM ANIMAL_INS
GROUP BY NAME
HAVING COUNT(NAME) > 1
) B ON A.NAME = B.NAME
ORDER BY A.NAME;
|
1. FROM절에 INNER 조인 사용
2. MAIN SELECT절에 DISTINCT 사용
- DISTINCT를 사용하지 않을 경우, 동명 동물 수 만큼 record가 반환 됨
1
2
3
4
5
6
7
8
9
10
|
WITH SUB AS (
SELECT NAME, COUNT(NAME) AS NAMECOUNT
FROM ANIMAL_INS
GROUP BY NAME
)
SELECT NAME, NAMECOUNT COUNT
FROM SUB
WHERE NAMECOUNT > 1
ORDER BY NAME;
|
1. 공통 표현식 (Common Table Expression, CTE) 사용
- A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times. The following discussion describes how to write statements that use CTEs.
🔗 소스 코드
GitHub
📚 참고 자료
MySQL :: MySQL 8.0 Reference Manual :: 13.2.20 WITH (Common Table Expressions)
13.2.20 WITH (Common Table Expressions) A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times. The following disc
dev.mysql.com