본문 바로가기
공부/SQL

프로그래머스 SQL 고득점 Kit - GROUP BY; MySQL

by thegreatjy 2022. 3. 3.
728x90

https://programmers.co.kr/learn/courses/30/parts/17044

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


1. 고양이와 개는 몇 마리 있을까?

SELECT ANIMAL_TYPE, count(*) as count
from ANIMAL_INS
group by ANIMAL_TYPE
having ANIMAL_TYPE in ('Cat', "Dog")
order by ANIMAL_TYPE;

 

2. 동명 동물 수 찾기

SELECT NAME, count(*) as count
from ANIMAL_INS
where NAME is not null
group by NAME
having count(*)>=2
order by NAME;

 

3. 입양 시각 구하기 (1)

SELECT HOUR(DATETIME) as HOUR, count(*) as COUNT
from ANIMAL_OUTS
where HOUR(DATETIME)>=9 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(*) FROM ANIMAL_OUTS WHERE HOUR(DATETIME) = @hour) as COUNT
FROM ANIMAL_OUTS
WHERE @hour < 23

 

.. 3,4는 구글링이고 심지어 4는 이해 잘 못함..띠용 mysql에서 변수 선언 첨 해봄


* IS NULL, IS NOT NULL

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL
WHERE column_name IS NULL

 

* HAVING

SELECT column_name(s)
FROM table_name

WHERE condition

GROUP BY column_name(s)
HAVING condition

ORDER BY column_name(s);

- 순서 주의!

- where vs having : where 처리 후 having/having 구절에는 count(), sum()과 같은 함수가 들어감

- group by 로 묶은 속성은 select 에 있음 

  (select title, count(id) 인 경우에는 group by title)

 

* 날짜 데이터 일부 추출

YEAR 	: 연도 추출
MONTH 	: 월 추출
DAY 	: 일 추출
HOUR 	: 시 추출
MINUTE 	: 분 추출
SECOND 	: 초 추출

SELECT HOUR(속성 이름)

https://www.w3schools.com/sql/sql_groupby.asp

 

SQL GROUP BY Statement

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

728x90