STUDY/DBMS

[프로그래머스 SQL 테스트] select 문제 풀이 정리 1

nnh 2023. 10. 23. 17:20
728x90

SELECT

 

1. 12세 이하인 여자 환자 목록 출력하기

 

 

내 답안)

SELECT pt_name, pt_no, gend_cd, age, 
case when tlno is null then 'NONE'
else tlno end as tlno
from patient
where age <= 12
and gend_cd = 'W'
order by age desc, pt_name

 

 

 

2. 재구매가 일어난 상품과 회원 리스트 구하기

 

 

내 답안)

SELECT user_id, product_id
from online_sale
group by user_id, product_id
having count(*) >= 2
order by user_id, product_id desc

 

 

 

3. 오프라인/온라인 판매 데이터 통합하기

 

 

내 답안)

SELECT date_format(sales_date, '%Y-%m-%d') as sales_date, product_id, user_id, sales_amount
from online_sale
where date_format(sales_date, '%Y-%m') = '2022-03'
union
select date_format(sales_date, '%Y-%m-%d') as sales_date, product_id, NULL as user_id, sales_amount
from offline_sale
where date_format(sales_date, '%Y-%m') = '2022-03'
order by sales_date, product_id, user_id

 

 

 

4. 아픈 동물 찾기

 

 

내 답안)

SELECT animal_id, name
from animal_ins
where intake_condition = 'Sick'
order by animal_id

 

 

 

5. 어린 동물 찾기

 

 

내 답안) 

SELECT animal_id, name
from animal_ins
where intake_condition != 'Aged'
order by animal_id

 

 

 

6. 동물의 아이디와 이름

 

 

내 풀이)

SELECT animal_id, name
from animal_ins
order by animal_id

 

 

 

7. 여러 기준으로 정렬하기

 

 

내 풀이)

SELECT animal_id, name, datetime
from animal_ins
order by name, datetime desc

 

 

 

8. 상위 n개 레코드

 

 

내 풀이)

SELECT name
from animal_ins
order by datetime
limit 1

 

 

 

9. 조건에 맞는 회원수 구하기

 

 

내 풀이)

SELECT count(*)
from user_info
where year(joined) = '2021'
and age > 19 and age < 30

 

 

 

 

 

728x90