
signups 테이블에는 있지만 confirmations 테이블에는 없는 id=6이 어떻게 null값이 안나올 수 있는지(내가 쓴 쿼리)
with cnt as (select user_id, sum(action = 'timeout') "timeout",
sum(action = 'confirmed') "confirmed",
sum(action = 'timeout' or action = 'confirmed') "both"
from confirmations
group by 1)
select a.user_id,
ifnull(round(confirmed/`both`,2), 0) "confirmation_rate"
from signups a left join cnt b
on a.user_id=b.user_id
group by 1
---
(다른 사람 쿼리)
SELECT
s.user_id,
ROUND(AVG(CASE WHEN c.action="confirmed" THEN 1 ELSE 0 END),2) AS confirmation_rate
FROM signups AS s
LEFT JOIN confirmations AS c
ON s.user_id = c.user_id
GROUP BY 1
confirmations 테이블에 없는 ID = 6 의 값이 Null로 나오는데 다른 쿼리에선 어떻게 Null이 아닌 0으로 나왔을까.1.
with total_price as (
select a.product_id,
a.price * b.units "sales",
units
from prices a left join unitssold b
on a.product_id=b.product_id and b.purchase_date between a.start_date and a.end_date
)
-------
2.
with total_price as (
select a.product_id,
a.price * b.units "sales",
units
from prices a left join unitssold b
on a.product_id=b.product_id
where b.purchase_date between a.start_date and a.end_date
)
prices 테이블에는 있고 UnitsSold 테이블에는 없는 ID = 3 이 조회된다.JOIN의
ON절: 조인 전 각 테이블에 있는 데이터에 조건 걸음
WHERE절: 조인 후의 데이터에 조건을 거는 것

select t1.col1, t1.col2, t2.col1, t2.col2
from table1 t1
left join table2 t2
on t1.col1 = t2.col1
and t2.col2 = '일'

select t1.col1, t1.col2, t2.col1, t2.col2
from table1 t1
left join table2 t2
on t1.col1 = t2.col1
where t2.col2 = '일'


따라서
left join unitssold b
on a.product_id=b.product_id and b.purchase_date between a.start_date and a.end_date
구매 날짜가 start_date, end_date에 포함하는 데이터가 매칭되어 join될 수 있었고,Leetcode 는 문법을 제대로 파악해야지만 이해할 수 있는 문제가 많다.
문제의 컨셉은 간단하지만, 원하는 결과물을 만들어내는 쿼리는 결코 얉은 지식으로는 풀기 어려운 문제가 많아 푸는데 시간이 많이 걸리고 왜 이렇게 나오는지도 해석이 오래걸렸다 😭