본문 바로가기
SQL/코딩테스트

[프로그래머스 / MySQL] 중복 제거하기

by Hi_heidi 2024. 1. 29.

문제

💡 동물 보호소에 들어온 동물의 이름은 몇 개인지 조회하는 SQL 문을 작성해주세요. 이때 이름이 NULL인 경우는 집계하지 않으며 중복되는 이름은 하나로 칩니다.

 

테이블 형태

테이블 / 출력 결과 예시

 

풀이

SELECT COUNT(DISTINCT NAME) FROM ANIMAL_IN

 

해설

SELECT COUNT(DISTINCT NAME) FROM ANIMAL_INS
  • DISTINCT 로 중복 제거하여 COUNT 해주었다

 

COUNT와 COUNT(DISTINCT )

MySQL 공식 문서 참고

 

MySQL :: MySQL 8.0 Reference Manual :: 14.19.1 Aggregate Function Descriptions

MySQL 8.0 Reference Manual  /  ...  /  Functions and Operators  /  Aggregate Functions  /  Aggregate Function Descriptions 14.19.1 Aggregate Function Descriptions This section describes aggregate functions that operate on sets of values. They are

dev.mysql.com

COUNT(컬럼명) COUNT(*) COUNT(DISTINCT 컬럼명)
NULL을 제외하고 해당 컬럼의 값 개수 반환  NULL을 포함한 행 개수 반환 NULL과 중복을 제외하고 해당 컬럼의 고유한 값 개수 반환
    • COUNT(expr) Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value. 
    • COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.
    • COUNT(DISTINCT expr ) Returns a count of the number of rows with different non-NULL expr values. If there are no matching rows, COUNT(DISTINCT) returns 0.