MySQL/programmers

[MySQL] 프로그래머스 SQL 고득점 kit - GROUP BY문

동현 유 2021. 3. 14. 22:21

아래와 같은 테이블이 있다고 하자.

 

 

예제1) 고양이와 개는 몇마리 있을까

SELECT ANIMAL_TYPE, count(animal_type) as 'COUNT' 
from animal_ins 
group by animal_type 
order by animal_type;

 

 

예제2) 동명 동물 수 찾기

SELECT NAME, COUNT  
from (
    SELECT NAME, count(NAME) as 'COUNT' from animal_ins
    where NAME != ''
    group by NAME
    order by NAME
) sq1 # sub-quary, select문은 테이블을 반환. 반환된 테이블은 이름을 반드시 갖고 있어야 함.
where COUNT > 1;

 

예제3) 입양 시각 구하기1

SELECT hour(datetime) as 'HOUR', count(datetime) as 'COUNT' 
from animal_outs 
where hour(datetime) > 8 and hour(datetime) < 20
group by hour(datetime)
order by hour(datetime);

 

예제4) 입양 시각 구하기2

set @hour := -1; # 변수선언

SELECT 
    (@hour := @hour + 1) as 'HOUR', 
    (SELECT count(hour(datetime)) from animal_outs where hour(datetime) = @hour) as 'COUNT' 
from animal_outs
where @hour < 23;

/* 
    HOUR 와 COUNT 를 뽑아내야 함.
    HOUR는 변수를 통해 한시간씩 뽑아냄.
    COUNT는 HOUR와 같은 시간을 세주어야함. => 서브쿼리를 이용하자!
*/