13일차_SQL 걷기반 문제 8,9,10,마지막 문제

김채윤·2025년 10월 16일


30번

Select name
From doctors
Where major=”성형외과”

31번

Select major,
      Count(1)
From doctor
Group by major

32번

Select count(*) number_of_doctor
From doctors
Where hire_date<=date_sub(curedate(), interval 5 year)

코드를 잘 몰라서 구글링을 통해 공부했다.

#curedate() ->오늘 날짜를 date타입으로 설정

#interval 5 year ->5년이라는 기간을 표현. Interval 3 month, interval 10 day, interval 2 hour처럼 쓸 수 있음

#date_sub(날짜, interval 기간) -> 지정한 날짜에서 기간을 뺌

#hire_date<=date_sub(curedat(), interval 5 year) ->hire_date가 오늘로부터 5년 전 날짜보다 더 옛날이거나 같을 것

Select count(*)
From doctor
Where year(hire_date)<=year(curedate)-5

내가 처음에 쓴 코드..가능은 하지만, 연도 숫자만 비교하기 대문에 만 5년이 안 된 사람도 포함될 수 있다.

추가로 where datediff>=365*5도 가능하지만 윤년 때문에 계산이 틀릴 수 있다.

33번

Select name,
      Datediff(curedate(), hire_date) working_days
From doctors

#datediff는 (나중 날짜(큰 숫자), 앞 날짜(작은 숫자))를 써야 양수가 나옴


34번

Select gender,
      Count(1)
From patients
Group by gender

35번

Select count(*)
From patients
Where birth_date<=date_sub(curedate(), interval 40 year)

36번

Select *
From patients
Where last_visit_date<=date_sub(curedate(), interval 1 year) 

Where datediff(curedate(), last_visit_date)>=365

를 처음에 작성했는데 윤년 때문에 정확히 1년이 아닐 수 있으므로 위가 더 적절하다.

37번

Select count(*)
From patients
Where birth_date between 1980-01-01 and 1989-12-31


38번

Select count(*)
From departments

39번

Select e.name,
      d.name
From employees e inner join departments d on e.department_id=d.id

40번

Select e.name
From employees e inner join departments d on e.department_id=d.id
Where d.name=’기술팀’

41번

Select d.name,
      Count(e.id)
From employees e left join departments d on e.department_id=d.id
Group by d.id

42번

Select d.name
From employees e left join department d on e.department_id=d.id
Where e.id is null 

43번

Select e.name
From employees e inner join department d on e.department_id=d.id
Where d.name=’마케팅팀’


44번

Select o.id,
      p.name
From orders o inner join products p on o.product_id=p.id

45번

Select p.id,
      Sum(price*quantity) ‘총 매출’
From orders o inner join products p on o.product_id=p.id
Group by p.id
Order by ‘총 매출’ desc
Limit 1

46번

Select p.id,
      Sum(quantity) sum_quantity
From product p inner join orders o on p.id=o.product_id
Group by p.id

47번

Select p.name
From orders o inner join products p on o.product_id=p.id
Where order_date>’2023-03-03’

48번

Select p.name,
      Sum(quantity) sum_quantity
From products p inner join orders o on p.id=o.product_id
Group by p.id
Order by sum_quantity desc
Limit 1

49번

Select p.id,
      Avg(quantity) avg_quantity
From products p inner join orders o on p.id=o.product_id
Group by p.id

50번

Select p.id,
      p.name
From product p left join orders o on p.id=o.product_id
Where o.id is null

0개의 댓글