본문 바로가기

전체 글15

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.
LeetCode_2. Basic Joins https://leetcode.com/studyplan/top-sql-50/1378. Replace Employee ID With The Unique Identifier문제 : 각 직원의 unique_id를 구하라. 없다면 nulljoin : from table이 왼쪽, join table이 오른쪽에 옴unique_id가 없더라도 이름을 전부 가져오기 위해서 left joinselect eu.unique_id, e.namefrom employees eleft join employeeuni eu on e.id = eu.id -- 공통 행(id) 기준으로 조인;1068. Product Sales Analysis I문제 : 상품 이름, 년도, 가격을 출력joinright join 시 Samsung 데이터도.. 2025. 3. 31.
LeetCode_1. Select https://leetcode.com/studyplan/top-sql-50/ 1757. Recyclable and Low Fat Products문제 : 저지방이고 재활용 가능한 제품의 ID 찾기select product_id from Productswhere low_fats = 'Y' and recyclable = 'Y ' -- 저지방, 재활용가능;584. Find Customer Refere문제 : id=2인 고객이 추천하지 않은 고객의 이름 찾기 select namefrom customerwhere referee_id != 2 or referee_id is null -- 추천인 id가 2가 아니거나 null값이 아님;595. Big Countries문제 : 대국의 이름, 인구, 면적 찾기sele.. 2025. 3. 31.
1. 기초 데이터 타입 및 테이블 관리 데이터 타입 이해하기 데이터베이스와 테이블의 기본 구조 테이블 수정 및 업데이트 방법 데이터 삽입 및 조회 기초 1. MySQL + HeidiSQL 설치 2. 데이터 타입 문자형 CHAR(n) VARCHAR(n) TEXT 숫자형 TINYINT SMALLINT MEDIUMINT INT BIGINT DECIMAL(n,d) 날짜형 DATE DATETIME TIME YEAR 3. DataBase/ Table unnamed에서 오른쪽 클릭 > 새로 생성 > DB > test 생성 CREATE, ALTER, DROP, TRUNCATE CREAT TABLE 테이블명 customers 테이블 생성 CREATE TABLE customers( customer_number INT, customer_name VARCHAR(5.. 2024. 1. 5.