On the journey of
[Leetcode] 1174.Immediate food delivery 2 , 619. Biggest Single Number,626.Exchange Seats 본문
[Leetcode] 1174.Immediate food delivery 2 , 619. Biggest Single Number,626.Exchange Seats
dlrpskdi 2023. 10. 6. 08:201. https://leetcode.com/problems/immediate-food-delivery-ii/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 자체는 그리 어렵지 않은데, Round 함수를 쓸 때 Round 함수 안의 변수에 case 및 쿼리문 일체를 쓸 줄 알아야 했다.
with base_table as (
select *, rank() over(partition by customer_id order by order_date) as ranking
from delivery )
select round(avg(case when order_date = customer_pref_delivery_date then 1.00 else 0.00 end)*100, 2) as immediate_percentage
from base_table
where ranking = 1
case when ~ 같은 부분을 의미하는데, Python의 if / else문을 알고 있었다면 이를 sql 상에서 case, when 절로 바꾸기만 하면 되는 거여서 낯설 뿐 아주 어렵진 않았다 :)
2. Biggest Single Number ) https://leetcode.com/problems/biggest-single-number/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Q. 소수를 의미하는 게 아니라, 임의의 리스트가 주어졌을 때 이 리스트 상에서 1번 등장한 숫자를 return하라는 것.
어떻게 시작해야 하나 좀 많이 ... 막막했다. 없다면 null을 반환하면 되고, 있다면 max이니까 select max(num)으로 시작해야 한다... 그리고 어떻게 할지 좀 막혔었어서 from 절에 그럼 뭘 넣을지 생각해봤다. 남는 조건을 where로 넘기려 했는데, 이미 max(num)에서 최대치임을 알려주고 있으니까..그렇게 정리한 것
select num을 한 후에 num이 쭉 나오면
1. 오름차순/내림차순으로 정렬한다
2. group by를 해서 같은 거끼리 묶어둔다
3. 묶은 다음 count를 해서 1개인 것만 추려낸다 => having count(num) = 1 이러면 되겠구나!
3-1. table 상에서 가져와야 하므로 table.counts = 1로 추려낸다
4. haveing count(num) = 1인 것 중 max인 것을 return한다
select
max(num) num
from
(
select num
from number
group by num
having
count(*) = 1
)
그리고 처참히 실패
무슨 에러인지 찾아보니 서브쿼리에 Alias(이름)를 주지 않았을 경우 발생하는 에러라고 한다. 오라클의 경우에는 서브쿼리에 Alias를 주지 않아도 정상적으로 동작하지만 leetcode는 MySQL 기반의 사이트이기에 무조건 오류가 발생한다고 한다! 하여,.. 이름 붙여줌. AS를 활용해서!
SELECT
MAX(num) AS num
FROM
(SELECT
num
FROM
MyNumbers
GROUP BY num
HAVING COUNT(num) = 1) AS t;
어려웠다,,,
3. 626)Exchange Seats : https://leetcode.com/problems/exchange-seats/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
mod 함수를 알고 있었다면 어렵지 않았을 것!
select next_id as id
, student
from (
select id as pre_id
, case
when MOD(ID,2) = 1 AND (id = (select max(id) from seat)) then id
when MOD(ID,2) = 1 then (id+1)
when MOD(ID,2) = 0 then (id-1)
end as next_id
, student
from seat
) as a
order by next_id asc