본문 바로가기

TIL 통합/SQL

TRUNCATE, CROSS JOIN 및 LEFT JOIN

코드카타

 

문제 158 Weather Observation Station 13

TRUNCATE 함수

 

 

Weather Observation Station 13 | HackerRank

Query the sum of Northern Latitudes having values greater than 38.7880 and less than 137.2345, truncated to 4 decimal places.

www.hackerrank.com

select truncate(sum(lat_n), 4)
from station
where lat_n > 38.7880 and lat_n < 137.2345

round함수와 비슷하지만, 반올림이 아니라 내림하는 함수.

어렵진 않지만 처음 써본 함수라 기록. 사실 문제에 truncate라는 동사가 있길래 그러면 truncate 함수도 있지 않을까?해서 써봤더니 정말로 있어서 어쩌다가 알아낸 함수였다.

 

 

1280.Students and Examinations 복습

CROSS JOIN, LEFT JOIN 활용

https://leetcode.com/problems/students-and-examinations/description/

 

오답

select e.student_id,
       s.student_name,
       su.subject_name,
       if(count(*) = Null, 0, count(*)) attended_exams
from subjects su join examinations e using(subject_name) join students s using(student_id)
group by 1, 2, 3
order by 1, 3

오답 이유

문제에서 원하는 아웃풋은 아래에서 볼 수 있뜻 count가 0인 것도 테이블에 표시가 되는 거였는데, 위와 같은 방식으로 하면 0인 행은 출력이 되지 않았다. 그래서 if절로 count가 null일 경우 0을 출력하라고 했으나 결과는 마찬가지(0일 경우도 마찬가지)

지난번에 풀었을 때에도 이런식으로 접근했던 것 같은데...암튼

 

정답

select s.student_id,
       s.student_name,
       su.subject_name,
       count(e.subject_name) attended_exams
from students s cross join subjects su left join examinations e using(student_id, subject_name)
group by 1, 2, 3
order by 1, 3

포인트

  1. 크로스 조인과 레프트 조인을 적절히 활용 : 최근에 자주 사용하지 않았더니 쓸 생각을 사실상 안 했던듯 하다..ㅎ
  2. examinations를 left join 하기 위해 칼럼 일치 시킬 때 student_id, subject_name 둘 다 사용할 것! : 안 그러면 아래 테이블처럼 student_id, student_name에 따른 그룹화 및 카운트가 제대로 이루어지지 않음

 

아웃풋

| student_id | student_name | subject_name | attended_exams |
| ---------- | ------------ | ------------ | -------------- |
| 1          | Alice        | Math         | 3              |
| 1          | Alice        | Physics      | 2              |
| 1          | Alice        | Programming  | 1              |
| 2          | Bob          | Math         | 1              |
| 2          | Bob          | Physics      | 0              |
| 2          | Bob          | Programming  | 1              |
| 6          | Alex         | Math         | 0              |
| 6          | Alex         | Physics      | 0              |
| 6          | Alex         | Programming  | 0              |
| 13         | John         | Math         | 1              |
| 13         | John         | Physics      | 1              |
| 13         | John         | Programming  | 1              |