[데이터분석] 부트캠프 TIL

20260105 TIL

myun0506 2026. 1. 5. 21:32

Today I Learn 

: 코드카타, 파이썬 강의, SQL 사전퀘스트 Lv4

 

- 코드카타 

- 문제 1 프로그래머스 (#21) 이름이 없는 동물의 아이디 

1. 문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/59039

2. 정답 코드: 

select animal_id
from animal_ins 
where name is null 
order by animal_id asc

 

- 문제 2 프로그래머스 (#22) 조건에 맞는 회원수 구하기 

1. 문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/131535

2. 정답 코드:

select count(*) 
from user_info 
where year(joined) = '2021' 
and age between 20 and 29

 

- 문제 3 프로그래머스 (#23) 중성화 여부 파악하기 

1. 문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/59409

2. 정답 코드:

select animal_id, name, 
       case 
       when sex_upon_intake like '%Neutered%' or 
            sex_upon_intake like '%Spayed%' then 'O'
       else 'X' end as '중성화'
from animal_ins 
order by animal_id

3. 오류 상황: like 와 in 은 한꺼번에 사용 불가능해서 오류 발생

4. 해결 방법: 문장을 따로 or 로 구분해줌

 

- 문제 4 프로그래머스 (#24) 카테고리 별 상품 개수 구하기 

1. 문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/131529

2. 정답 코드:

select substr(product_code,1,2) as category,
       count(*) as products
from product
group by 1

 

- 문제 5 프로그래머스 (#25) 고양이와 개는 몇 마리 있을까

1. 문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/59040

2. 정답 코드: 

select animal_type, count(*) as count
from animal_ins 
group by 1
order by (case when animal_type = 'cat' then 1 else 2 end)

 

  • 특정 값을 기준으로 정렬
    • order by (case when 특정 열 = 특정 값 then 1 else 2 end) 

 

- 파이썬 특강 

 

https://myun0506.tistory.com/52

 

입출력, 변수, 문자열

1) 입출력 (Input / Output) sep 옵션 (기본값: sep = ' ' (공백))print(2026, 1, 4, sep="/") # 2016/1/4print("사과", "바나나", "포도", sep=", ") # 사과, 바나나, 포도print("2", "0", "2", "6", sep="") # 2026 end 옵션 (기본값: end = '

myun0506.tistory.com

 

 

 

- SQL 사전 퀘스트

 

- Lv4. 가장 높은 월급을 받는 직원은?

( 코드: https://github.com/rladbstj56/2025_pre_bootcamp/blob/main/SQL_Lv4_high_salary )

  • 문제 1
# 내가 쓴 쿼리
with ranked as (
select 
	employeeid,
	name, 
	department, 
	row_number() over (partition by department order by salary desc) 
		as rnk, 
	salary
from basic.employees2 
), 
final_ranked as ( 
select r.name, r.department, r.salary 
from ranked r 
where rnk = 1
) 
select e.name, e.department, e.salary, f.name, f.salary 
from basic.employees2 e
join final_ranked f
on e.department = f.department
# 정답 쿼리
select e1.name, e1.department, e1.salary,
	   e2.name as top_earner, e2.salary as top_salary
from basic.employees2 e1
join basic.employees2 e2 on e1.department = e2.department 
where e2.salary = ( 
	select max(salary) 
	from basic.employees2 e3
	where e3.department = e1.department
	);
  • e3: e1기준으로 봤을 때 각 행의 사람의 부서 총 직원중에 가장 높은 월급을 구해라.
    • 따라서 e1.department = e3.department
  • e1 (바깥쪽 명단): 지금 내가 한 명씩 검사하고 있는 전체 직원 명단
  • e3 (서브쿼리 안쪽 명단): "우리 부서 최고 월급이 누구지?"라고 찾아볼 때 사용하는 별도의 참고용 명단

 

  • 문제 2
# 내가 작성한 쿼리
with highest as (
select 
	department, 
	avg(salary) as avg_sal, 
	rank() over (order by avg(salary) desc) as rnk
from basic.employees2
group by department
) 
select h.department, h.avg_sal 
from highest h
where h.rnk = 1


# 정답 쿼리 
select department, avg(salary)
from basic.employees2 
group by department 
having avg(salary) = ( 
	select max(avg_salary) 
	from 
		(select avg(salary) as avg_salary 
		 from basic.employees2 
		 group by department) as subquery
	);

 

 

- 평균 월급보다 높은 직원들만 추출하면서 동시에 평균 월급도 같이 보고 싶을때

  • from 절에 서브쿼리 넣기
select 
    e.name, 
    e.salary, 
    s.avg_sal
from basic.employees e
join (
    select avg(salary) as avg_sal 
    from basic.employees
) s on 1=1  -- 모든 행에 평균값을 붙이기 위해 무조건 참인 조건 사용
where e.salary > s.avg_sal;

 

  • 윈도우 함수 사용하기
select name, salary, avg_sal
from (
    select 
        name, 
        salary, 
        avg(salary) over() as avg_sal -- 전체 평균을 옆에 바로 계산
    from basic.employees
) sub
where salary > avg_sal;

 

 

 

- 부서별로 평균 월급이 가장 높은 부서를 찾고, 그 부서에 속한 직원들의 이름, 월급, 그리고 해당 부서의 평균 월급을 조회하기 (단, 윈도우 함수 over()를 사용하지 말고 서브쿼리만 활용해서 작성하기)

with selected as (
select department, avg(salary) as avg_sal # 평균 월급이 가장 높은 부서
from employees
group by department
having avg(salary) = (
	select max(avg_sal)
	from 
	(
	select department, avg(salary) as avg_sal 
	from employees 
	group by department
	) as subquery
)
) 
select e.name, e.salary, s.avg_sal
from employees e
inner join selected s
on e.department = s.department

 

 

- join이나 with 절을 쓰지 말고, select 절 안에 서브쿼리를 직접 넣어서 모든 직원의 이름, 부서, 월급, 그리고 '그 직원이 속한 부서의 평균 월급'을 조회하기

  • 윈도우함수 사용
select
	name,
	department, 
	salary, 
	avg(salary) over (partition by department) as avg_sal
from employees

 

  • 상관 서브쿼리 사용
    • select 안의 서브쿼리에서도 외부 쿼리의 값을 가져다 쓸 수 있다!!!
select
	name,
	department, 
	salary, 
	(select avg(salary) 
	 from employees e2
	 where e2.department = e1.department)
from employees e1

 

 

 

 

- 프로그래밍 기초주차 시작

 

아 저번주에 우리 zep에서 뛰댕기는뎈ㅋㅋㅋㅋㅋ

어떤분이 3조 러닝크루냐고 한거 개웃겼음 ㅜㅜㅜㅜㅜㅜ

그리고 또 누가 알짱거려서

우리 네명이 다같이 콕찌르기 했더니 '지나가다 패시는데요' 이러신거

개웃겨!!!!!!!!!!! ㅜㅜㅜ

 

 

너무 애틋한 우리 삼조...?

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ

여러분과 카페(zep)에서 다시 만나길,,,

'[데이터분석] 부트캠프 TIL' 카테고리의 다른 글

20260107 TIL  (1) 2026.01.07
20260106 TIL  (0) 2026.01.06
20260102 TIL  (1) 2026.01.02
20260101 TIL  (0) 2026.01.01
20251231 TIL  (0) 2025.12.31