본문 바로가기

전체 글44

[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.
[LeetCode 627] Swap Salary 하나의 update 구문을 이용하여 테이블의 성별을 바꿔보자 SQL update는 다음과 같이 나타낸다. UPDATE 테이블명 SET 컬럼 = 변경할 값 WHERE 조건 이 경우에는 where 절 없이 set에 case when을 사용할 수 있다. update salary set sex = case when sex= 'm' then 'f' else 'm' end ; 제출 코드 보니까 각각 지정해주는게 더 빠르더라 update Salary set sex = case when sex = 'm' then 'f' when sex = 'f' then 'm' end ; 2023. 1. 28.
[LeetCode 1873] Calculate Special Bonus 이름이 M으로 시작하지 않고 id가 홀수인 사람들에게 급여만큼의 보너스를 주려고 한다. id 내림차순으로 정렬하여 보너스를 계산해보자. 나는 아래와 같이 제출하였는데, select employee_id , case when (left(name,1) != 'M') and (employee_id % 2 = 1) then salary else 0 end as bonus from employees order by employee_id; 요렇게도 표현할 수 있더라 select employee_id , case when (name not like 'M%') and (employee_id %2 0) then salary else 0 end as bonus from employees order by employee_id; 2023. 1. 28.
[LeetCode601] Human Traffic of Stadium 방문자수가 100이 넘는, id가 연속으로 3 이상인 경우만 나타내보려고 한다. lead와 leg를 사용하여 케이스를 만든다. select id, visit_date, people from (select id, visit_date, people, lead(people, 1) over (order by id) as after1, lead(people, 2) over (order by id) as after2, lag(people, 1) over (order by id) as pre1, lag(people, 2) over (order by id) as pre2 from stadium) as A where A.people>99 and ((A.after1>99 and A.after2>99) or (A.pre1 .. 2023. 1. 23.