- 아티클 스터디 2개
- 엑셀보다 쉽고 빠른 SQL 5주차
SELECT restaurant_name,
avg(rating) avg_rating,
avg(if(rating <> 'Not given', rating, null)) null_rating
FROM food_orders fo
GROUP BY 1
select a.order_id,
a.customer_id,
a.restaurant_name,
a.price,
b.name,
b.age,
b.gender
from food_orders a left join customers b on a.customer_id=b.customer_id
where b.customer_id is not null
1) IF문 활용
select a.order_id,
a.customer_id,
a.restaurant_name,
a.price,
b.name,
b.age,
coalesce(b.age, 20) "null 제거",
b.gender
from food_orders a left join customers b on a.customer_id=b.customer_id
where b.age is null

[예시1]
select restaurant_name,
max(if(hh='15', cnt_order, 0)) "15", -- 15시 칼럼
max(if(hh='16', cnt_order, 0)) "16", -- 16시 칼럼
max(if(hh='17', cnt_order, 0)) "17", -- 17시 칼럼
max(if(hh='18', cnt_order, 0)) "18", -- 18시 칼럼
max(if(hh='19', cnt_order, 0)) "19", -- 19시 칼럼
max(if(hh='20', cnt_order, 0)) "20" -- 20시 칼럼
from
(
select a.restaurant_name,
substring(b.time, 1, 2) hh,
count(1) cnt_order
from food_orders a inner join payments b on a.order_id=b.order_id
where substring(b.time, 1, 2) between 15 and 20
group by 1, 2
) a - 이 서브쿼리가 DB
group by 1
order by 7 desc
[예시2]
SELECT a.age,
MAX(IF(a.gender = 'male', cnt_order, 0)) 'male',
MAX(IF(a.gender = 'female', cnt_order, 0)) 'female'
FROM (
SELECT c.gender,
CASE WHEN c.age BETWEEN 10 AND 19 THEN 10
WHEN c.age BETWEEN 20 AND 29 THEN 20
WHEN c.age BETWEEN 30 AND 39 THEN 30
WHEN c.age BETWEEN 40 AND 49 THEN 40
WHEN c.age BETWEEN 50 AND 59 THEN 50 END 'age',
COUNT(*) cnt_order
FROM food_orders fo INNER JOIN customers c ON fo.customer_id = c.customer_id
WHERE c.age BETWEEN 10 AND 59
GROUP BY 1, 2
) a
GROUP BY 1
ORDER BY age
WINDOW_FUNCTION() OVER (PARTITION BY 그룹 기준 칼럼 ORDER BY 정렬 기준)
SELECT cuisine_type, restaurant_name, cnt_order, ranking
FROM
(SELECT cuisine_type,
restaurant_name,
cnt_order,
RANK() OVER (PARTITION BY cuisine_type ORDER BY cnt_order DESC) ranking
FROM (
SELECT cuisine_type,
restaurant_name ,
COUNT(*) cnt_order
FROM food_orders fo
GROUP BY 1, 2
) a
) b
WHERE ranking <= 3
SELECT cuisine_type, restaurant_name, cnt_order,
SUM(cnt_order) OVER (PARTITION BY cuisine_type) sum_cuisine,
SUM(cnt_order) OVER (PARTITION BY cuisine_type ORDER BY cnt_order) cum_cuisine
FROM (
SELECT cuisine_type,
restaurant_name,
COUNT(1) cnt_order
FROM food_orders
GROUP BY 1, 2
) a
ORDER BY cuisine_type, cnt_order
DATE_FORMAT(date type 칼럼, '%__')
- %Y 연도 (두 자리)
select date(date) date_type,
date_format(date(date), '%Y') "년",
date_format(date(date), '%m') "월",
date_format(date(date), '%d') "일",
date_format(date(date), '%w') "요일"
from payments