본문 바로가기

learning/SQL17

[LeetCode 176] Second Highest Salary 두번째로 높은 급여를 반환하자. 없으면 null을 반환한다. 다음 구문에 대해 알아보자 ifnull : 조건 값이 있을 때는 그 값을, 없을 때는 지정 값을 반환한다. ifnull(조건, null 일 때의 값) 으로 나타낸다. offset : limit과 같이 쓰이며, 몇번째부터 샐 지 나타낸다. 5번째 행 부터 3개를 나타내고 싶으면 LIMIT 3 OFFSET 5 으로 나타낼 수 있다. 위 문제는 간단하게 최댓값을 필터링한 후 가장 높은 값을 뽑을 수 있다. 속도도 제일 빠르다. SELECT MAX(Salary) AS SecondHighestSalary FROM Employee WHERE Salary not in (SELECT MAX(Salary) FROM Employee); ifnull 조건을 걸 수.. 2023. 1. 29.
[LeetCode 1667] Fix Names in a Table 이름의 첫 글자는 대문자로, 나머지는 소문자로 바꿔보자. 첫글자를 지정하는데 left, 대문자를 지정하는데 upper를 사용하고 그 외 글자는 substring과 lower을 사용한다. 두 덩어리를 합치는데 concat을 사용한다. substring은 SUBSTRING(글자, 시작위치, 길이) 으로 나타내고, 시작위치는 1부터 시작한다. 이 경우에는 두번째 글자부터 긁어오기 때문에 2라고 넣었다. select user_id, concat( upper(left(name,1)), lower(SUBSTRING(name,2)) ) as name from users order by user_id; 2023. 1. 28.
[LeetCode 1527] Patients With a Condition conditon에 접두사 DIAB1 가 붙는 것들만 필터링해보자. like 로 쉽게 해결 가능하다. '%DIAB1%' 로 제출했더니 SDIAB1 같은 경우가 있어서 두 경우로 나누어줬다. select patient_id, patient_name, conditions from Patients where conditions like 'DIAB1%' or conditions like '% DIAB1%'; 꼼수라고 생각해는데 다 이렇게 하더라,, 2023. 1. 28.
[LeetCode 608] Tree Node node의 타입을 구분해보자. case when 사용하면 된다. select id, (case when p_id is null then 'Root' when id in (select p_id from tree) then 'Inner' else 'Leaf' end ) as type from tree case when 구문 안 select 절에 distinct(p_id)했는데 distinct 빼는 것이 더 빠르더라 2023. 1. 28.
[LeetCode 1965] Employees With Missing Information 정보가 한쪽이라도 누락된 id를 찾자 full outer join을 만들기 위해 union을 사용한다. (select e.employee_id from employees as e left join salaries s on e.employee_id = s.employee_id where s.salary is null) union (select s.employee_id from employees as e right join salaries s on e.employee_id = s.employee_id where e.name is null) order by employee_id ; 다 풀어놓고,, where절 바꿔서 한참 헤맸다 허허 2023. 1. 28.
[LeetCode 196] Delete Duplicate Emails 중복되는 이메일을 삭제하자. id는 가장 작은 것을 남겨둔다. SQL에서 delete 구문은 다음과 같이 나타낸다. DELETE FROM 테이블명 WHERE 조건; 위 문제는 두가지 방법으로 접근할 수 있다. 1. join 사용하여 조건을 필터링하는 방법 DELETE p1 FROM Person p1 INNER JOIN Person p2 ON p1.email = p2.email where p1.id > p2.id; 2. where에 select 구문을 넣는 방법 delete from person where id not in (select * from (select min(id) from person group by email) as p) 2023. 1. 28.