[241024] SQL Greatest 함수

JunichiK·2024년 10월 24일

SQL 스터디

목록 보기
20/21

문제 & 제출 답안

  • 1731. The Number of Employees Which Report to Each Employee

    # Write your MySQL query statement below
    SELECT e1.employee_id, e1.name, count(e2.reports_to) reports_count, round(avg(e2.age),0) average_age 
    FROM employees e1
    INNER JOIN employees e2
    ON e1.employee_id = e2.reports_to
    GROUP BY 1
    ORDER BY 1

    🔒 구해볼 것 : 다른 사람에게 보고 받는 직원의 ID, 이름, 보고 직원 수, 보고 직원 평균 나이

    🔑 세부 구현

    1. employee_id 와 reports_to 로 이너 조인
    2. employee_id로 그룹바이
    3. count(reports_to)
    4. round(avg(age),0)
  • 1789. Primary Department for Each Employee

    SELECT employee_id, department_id
    FROM employee
    WHERE employee_id not in
            (SELECT employee_id
            FROM employee
            WHERE primary_flag = 'Y')
    union all
    SELECT employee_id, department_id
    FROM employee
    WHERE primary_flag = 'Y'

    🔒 구해볼 것 : 모든 직원들의 1차 부서 구하기 (하나만 조인되어 있으면 N)

    🔑 세부 구현

    1. WHERE primary_flag = ‘Y’
    2. WHERE primary_flag = ‘N’
    3. union all
    4. employee_id, department_id 출력
  • 610. Triangle Judgement

    SELECT *, CASE WHEN greatest(x, y, z) * 2 < x + y + z then 'Yes'
            ELSE 'No' end as triangle
    FROM triangle

    🔒 구해볼 것 : 삼각형 가능 여부 출력
    🔑 세부 구현

    1. 가장 긴 변의 길이 < 나머지 두 변의 길이 합
    2. 가장 큰 값 출력
      • greatest 함수 사용
    3. 가장 큰 값 < 나머지 두 값의 합일 경우, Yes 아님 No
      • greatest(x, y, z) < x + y + z
      • Case when
  • 180. Consecutive Numbers

    # Write your MySQL query statement below
    SELECT distinct num as ConsecutiveNums
    FROM
    (
    SELECT num,
        lag(num, 2) over() as num2,
        lag(num) over() as num1
    FROM logs
    ) A
    WHERE num = num2 and num = num1

    🔒 구해볼 것 : 세 번 이상으로 연속 출력된 숫자 구하기

    🔑 세부 구현

    1. 두번째 전, 첫번째 전 숫자 출력
      • LAG(num, 2) over ()
      • LAG(num) over ()
    2. 두번째, 첫번째 전과 현재 숫자가 동일한 숫자 출력
      • WHERE num = num1 and num = num2

오답노트

greatest 함수

💯 정답 (혹은 더 좋은 답)

   SELECT *, CASE WHEN greatest(x, y, z) * 2 < x + y + z then 'Yes'
           ELSE 'No' end as triangle
   FROM triangle

😅 내가 쓴 답

   -- 정답과 동일
   SELECT *, CASE WHEN greatest(x, y, z) * 2 < x + y + z then 'Yes'
           ELSE 'No' end as triangle
   FROM triangle
  • 틀린 이유 : greatest() 함수 몰랐음
  • 알게 된 문법 : greatest(컬럼 1, 컬럼 2, …)
    • 컬럼 1, 컬럼 2, … 중 가장 큰 컬럼 값 출력
profile
represent ojeong-dong

0개의 댓글