본문 바로가기

SQL9

SubQuery, SelfJoin, WindowFunction 비교 하나의 문제를 해결할 때 Subquery, SelfJoin, Window Function은 서로 다른 방식으로 활용될 수 있다.따라서 각각의 사용 방식을 구분하여 정리해두고자 한다.. SubQuery : 쿼리 안에 또 다른 쿼리를 중첩 사용SELECT ...FROM tableWHERE column IN (SELECT ... FROM ...);> 특정 조건에 맞는 값 조회, 필터링, 비교, 임시 테이블 특정 기준값 만들기(max, min, avg...)특정 조건을 만족하는 행만 필터링외부 쿼리와 값을 비교특징WHERE, FROM, SELECT 절에서 조건 생성한번만 실행되고, 외부 쿼리에 값을 전달함결과가 스칼라. 리스트, 테이블 모두 가능단순하면 빠름, 중첩이 많아지면 느려짐Self Join : 같은 테.. 2025. 4. 5.
LeetCode_7. Advanced String Functions / Regex / Clause https://leetcode.com/studyplan/top-sql-50/1667. Fix Names in a Table문제 : 이름의 첫 번째 문자만 대문자, 나머진 소문자로 변환Concat() : 문자열 합치기Left + Substring select user_id, concat( upper(left(name, 1)), -- 대문자(첫 글자) lower(substring(name, 2)) -- 소문자(두 번째 글자부터 끝까지 추출) ) as namefrom usersorder by 1;1527. Patients With a Condition문제 : 제 1형 당뇨병 환자의 정보 추출 (: DIAB1 접두사로 시작)regexp_like : 글자 위치, 시작/ 끝, 주변 문자.. 2025. 3. 31.
LeetCode_6. SubQueries https://leetcode.com/studyplan/top-sql-50/ 1978. Employees Whose Manager Left the Company문제 : 월급이 $30000 미만이고, 매니저가 퇴사한 직원 정보 구하기1. salary 1의 매니저는 112. 11 직원은 6 매니저가 있음 (manager_id is not null)3. 6 매니저의 정보는 없음 (퇴사, employee_id is null)select employee_idfrom employeeswhere salary 626. Exchange Seats문제 : 연속되는 id를 가진 두 학생의 좌석 바꾸기mod(5, 2) = 1 : 나머지 구하기('나누는 수가 0이면 null값으로 처리한다' case, if, where 쿼리.. 2025. 3. 31.
LeetCode_5. Advanced Select and Joins https://leetcode.com/studyplan/top-sql-50/ 1731. The Number of Employees Which Report to Each Employee문제 : Write a solution to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer. > 1명 이상의 report를 받는 매니저의 employee_id, name, reports_count, average_age 찾기join (self join)- reports_to 열은 .. 2025. 3. 31.
LeetCode_4. Sorting and Grouping https://leetcode.com/studyplan/top-sql-50/2356. Number of Unique Subjects Taught by Each Teacher문제 : 각 교사가 대학에서 가르치는 고유 과목의 수 계산1. group by로 teacher_id의 데이터 묶기 (1, 2)2. count(distinct ( ) ) 로 (1, 2)의 subject_id 중복제거 후 개수 세기select teacher_id, count(distinct(subject_id)) as cntfrom teachergroup by 1;1141. User Activity for the Past 30 Days문제 : 2019년 7월 27일까 30일 동안의 일일 활성 사용자 수 찾기 (적어도 하나의 활동을 했다면 .. 2025. 3. 31.
LeetCode_3. Basic Aggregate Functions https://leetcode.com/studyplan/top-sql-50/620. Not Boring Movies문제 : 홀수번호 중 지루하지 않은 영화 추출 select * from cinema where id % 2 = 1 and description = 'boring' order by rating ;1251. Average Selling Price문제 : 각 제품이 판매된 기간의 평균 판매 단가 구하기ifnull( 반환 값, null일 경우 대체 값 )select p.product_id, ifnull(round(sum(p.price * u.units) / sum(u,units), 2), 0) as average_price --단가계산, null은 0으로 대체from prices pleft join.. 2025. 3. 31.