learning/SQL17 [LeetCode 1084] Sales Analysis III 2019년 1 분기에만 팔린 제품들을 알아보자. join 해서 날짜 필터링 해주면 된다. distinct 안 넣었다가 틀렸다. select distinct(p.product_id), (p.product_name) from Product as p join sales as s on p.product_id = s.product_id where s.product_id not in (select distinct(product_id) from sales where sale_date date("2019-03-31")) and s.sale_date >= date("2019-01-01") and s.sale_date 2023. 1. 31. [LeetCode 1141] User Activity for the Past 30 Days I 2019-07-27을 포함한 이전 30일에 대해 날짜별 참여자 수를 세어보자 지난번에 배운 date_add 를 사용할 수 있다. 그리고 date 안에는 따옴표로 감싸줘야 한다는 것을 알게되었다. select activity_date as day, count(distinct(user_id)) as active_users from Activity where activity_date date_add(date("2019-07-27"), interval -30 day) group by activity_date 2023. 1. 31. [LeetCode 607] Sales Person 'RED' 회사와 일하지 않은 사람 id를 반환하자. 간단하게 join해서 풀 수 있다. select name from salesperson where sales_id not in (select o.sales_id from orders as o join company as c on o.com_id = c.com_id where c.name = 'RED') ; 아래는 처음 제출한 코드. join이 하나 필요 없어서 뺐는데 왜 이 코드가 더 빠른 걸까. select d.name from salesperson as d where d.sales_id not in (select o.sales_id from salesperson as s join orders as o on o.sales_id = s.sales_id.. 2023. 1. 30. [LeetCode 197] Rising Temperature 전날대비 기온이 오른 날을 반환하자. 날짜를 쉽게 계산할 수 있는 date_add를 알아보자. date_add(날짜, interval 원하는기간) 으로 나타낸다. select w.id from weather as w left join (select id, temperature, date_add(recorddate,interval 1 day) as y from weather ) as p on w.recorddate = p.y where w.temperature > p.temperature; lag로 헤매고 있었는데 ㅎㅎㅎ 2023. 1. 30. [LeetCode 1158] Market Analysis I buyer가 2019년에 주문한 건수를 세 보자. 2019년도 주문 건수를 count로 세고 ifnull로 없는 사람들을 0으로 채웠다. select u.user_id as buyer_id , u.join_date, ifnull(o.orders_in_2019,0) as orders_in_2019 from users as u left join (select buyer_id, count(*) as orders_in_2019 from Orders where year(order_date) = 2019 group by buyer_id ) as o on o.buyer_id = u.user_id ; 2023. 1. 29. [LeetCode 1393] Capital Gain/Loss 종목별 이익을 계산하자. case when 이용하였다. select stock_name, sum( case when operation='Buy' then -price else price end) as capital_gain_loss from stocks as s group by s.stock_name ; operation day도 계산에 넣는 줄 알았는데,, 문제를 잘 읽자,,,,,, 2023. 1. 29. 이전 1 2 3 다음