문제/프로그래머스_sql

23. 오랜 기간 보호한 동물(2)

sm_hope 2022. 10. 26. 19:06
SELECT ANIMAL_ID, NAME
from(
    SELECT ins.ANIMAL_ID, ins.NAME,(outs.DATETIME - ins.DATETIME) as time 
    FROM ANIMAL_INS as ins
    left join ANIMAL_OUTS as outs
    on ins.ANIMAL_ID = outs.ANIMAL_ID
    order by time desc
    limit 2
) a

혹은

    SELECT ins.ANIMAL_ID, ins.NAME
    FROM ANIMAL_INS as ins
    left join ANIMAL_OUTS as outs
    on ins.ANIMAL_ID = outs.ANIMAL_ID
    order by (outs.DATETIME - ins.DATETIME) desc
    limit 2

 

문제

: 보호기간이 가장 긴 동물 두 마리의 아이디와 이름을 조회하며, 보호기간이 긴 순으로 조회함.

 

서브쿼리를 이용해서 시간을 정의해주고자 했으나, order by에서 바로 처리도 가능하다.