본문 바로가기

learning/SQL17

[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.
[LeetCode262] Trips and Users 택시 이용 기록 테이블과 사람정보 테이블을 이용하여 날짜별 취소 비율을 계산해보자. 고객이나 기사가 블랙리스트에 올라가있다면 그 건수는 세지 않는다. 놀랍게도,, 테이블을 join하지 않고도 풀 수 있다. where 에 블랙리스트가 아닌 경우를 필터링 해주고 비율을 case when으로 설정해준다. select request_at as Day, round(count(case when status != 'completed' then 1 end)/count(id),2) as 'Cancellation Rate' from trips where client_id not in (select users_id from users where banned='Yes') and driver_id not in (select u.. 2023. 1. 21.
[LeetCode185] Department Top Three Salaries 연봉 정보 테이블과 부서 정보 테이블을 병합하여 부서별 unique한 값으로 top3 연봉 받는 사람을 나타내보자. 테이블 병합까지는 쉬운데 부서별 top 3를 어떻게 나타낼 것인가. 우선 연봉에 순위를 매긴다. 같은 값에 대해 같은 순위를 부여하고 그 외 순차적인 값을 매기는 dense_rank 를 사용한다. 연봉 높은 순이므로 over 뒤에는 order by salary desc 가 들어가야 한다. 두번째로 부서별 정보를 넣는다. partition by 를 이용하면 그룹별 집계를 쉽게 할 수 있다. select Department, Employee, Salary from (select d.name as Department, e.name as Employee, e.salary as Salary, den.. 2023. 1. 21.