Sparta/CODEKATA

[250818] 스파르타코딩 본캠프 10일차 (2)

junecho 2025. 8. 18. 15:06

💥  CODEKATA                                                                                                           

~35문제

 

26) 입양 시각 구하기

SELECT hour(datetime) as hour, count(1)
from animal_outs
group by hour
having hour between 0 and 23
order by hour

 

 

 

 

27) 진료과별 총 예약 횟수 출력하기

### 내코드
SELECT mcdp_cd as '진료과코드', count(1) as '5월예약건수'
from appointment
where apnt_ymd like '2022-05%'
group by mcdp_cd
order by '5월예약건수', '진료과코드'
### 답코드
SELECT mcdp_cd as '진료과코드', count(1) as '5월예약건수'
from appointment
where apnt_ymd like '2022-05%'
group by mcdp_cd
order by 5월예약건수, 진료과코드    -- 혹은 order by `5월예약건수`, `진료과코드`

⇒ 결과는 맞는데 자꾸 오답으로 출력됨 Why ? :

한글로 별칭을 지정하니까 ‘’ 작은따옴표를 무조건 써야될 것 같은 착각에 빠져 실수함

group by, order by, having 절에서 별칭을 쓸 경우, 별칭 그대로 쓰거나 백틱(~물결의 일반 출력 ``` )

으로 별칭을 감싸고 써야함 ! 아니면 숫자로 2, 1 이렇게 써도됨



 

 

30) 자동차 종류 별 특정 옵션이 포함된 자동차 수 구하기

### 내코드
SELECT car_type, count(1) as cars
from car_rental_company_car
where options like '%통풍시트%' or options like '%열선시트%' or options like '%가죽시트%'
group by car_type
order by car_type
### 코드 길이를 더 줄이고 싶다면 "시트" 라는 단어가 중복되므로 %시트% 사용
SELECT car_type, count(1) as cars
from car_rental_company_car
where options like '%시트%'
group by car_type
order by car_type

⇒ 흠.. like 3번 쓰는 것 보다 훨씬 좋은 코드가 있을 것 같아서 서치해봤는데 like 말고는 방법이 없음

맨 처음엔 in 으로 해서 찾아야지 했는데 안됨

in 은 값이 정확히 ‘통풍시트’ or ‘열선시트’ or ‘가죽시트’ 와 일치 하는 경우만 참

options 컬럼은 문자열들이 나열되어 있고 콤마(,) 로만 구분되어 있기 때문에 in을 사용하기 부적절

부문 문자열 검색인 like 를 쓰는게 맞긴 한데… 정녕 like ‘%시트%’ 말고는 줄일 방법이 없단 말인가



 

 

34) 있었는데요 없었습니다

### 내코드
select a.animal_id, a.name
from (
    SELECT ai.animal_id, ai.datetime, ai.name,
            datediff(ao.datetime, ai.datetime) as wrongdate
    from animal_ins ai left join animal_outs ao on ai.animal_id = ao.animal_id
) a
where a.wrongdate < 0
order by a.datetime
### 답코드
SELECT ai.animal_id, ai.name
from animal_ins ai left join animal_outs ao on ai.animal_id = ao.animal_id
where ai.datetime > ao.datetime
order by ai.datetime

⇒ 결과는 같음.

BUT 날짜로만 크고작음을 비교할 수 있는지 몰랐어서 datediff 로 날짜를 빼고, # 뺀 날짜가 0일 이상일 경우를 구하느라 쓸데없는 서브쿼리까지 써서 길어짐

 

 


ETC
더보기

1조 시작

코드리뷰 처음 해봤는데 어떻게 설명해야 할지 감이 안옴

문제 조건에 맞춰서 함수 쓰고 끝인데 어떻게 설명해야되지 흠