Day 15. ํ์ํ ๋ฐ๋ฆ์ด ์ ๋ฅ์ ์ฐพ๊ธฐ 2
https://solvesql.com/problems/find-unnecessary-station-2/
with t1 as (
SELECT rent_station_id, DATE_FORMAT(rent_at, '%Y-%m') as rent_at
, return_station_id-- , DATE_FORMAT(return_at, '%Y-%m') as return_at
FROM rental_history
where DATE_FORMAT(rent_at, '%Y-%m') = '2018-10'
or DATE_FORMAT(rent_at, '%Y-%m') = '2019-10'
), t2 as (
select DISTINCT rent_station_id as station_id
, count(case when rent_at = '2018-10' then rent_station_id end) over(PARTITION by rent_station_id) as cnt_18
, count(case when rent_at = '2019-10' then rent_station_id end) over(PARTITION by rent_station_id) as cnt_19
from t1
union all
select DISTINCT return_station_id as station_id
, count(case when rent_at = '2018-10' then return_station_id end) over(PARTITION by return_station_id) as cnt_18
, count(case when rent_at = '2019-10' then return_station_id end) over(PARTITION by return_station_id) as cnt_19
from t1
), t3 as (
select station_id
, round(sum(cnt_19) / sum(cnt_18)*100,2) as usage_pct
from t2
group by station_id
having (sum(cnt_18) / 2 ) >= sum(cnt_19) and usage_pct > 0
)
select t3.station_id, s.name, s.local, t3.usage_pct
from t3
inner join station as s on t3.station_id = s.station_id
โINNER JOIN์ผ๋ก ๊ณ์ฐํ ํ ์ด๋ธ ๊ฒฐํฉ ํ ์ํ๋ ์กฐ๊ฑด์ ์นผ๋ผ SELECT
+) WITH ์ : T1
โWHERE ์ ์ ๋ ์ง๊ฐ 2018-10 OR 2019-10์ธ ๊ฒ๋ง ํํฐ๋ง
+) WITH ์ : T2
โDISTINCT ์ฌ์ฉํด์ ๊ณ ์ ์ station_id ์ถ์ถ
โCOUNT(), CASE WHEN, ์๋์ฐ ํจ์ ์ฌ์ฉํด์ ์ฐ์์ ๋ฐ๋ผ ๊ฐ์ ์ธ๊ธฐ
โrent์ return ์ ๊ฐ๊ฐ ๊ตฌํ๊ณ UNION ALL๋ก ํฉ์น๊ธฐ
+) WITH ์ : T3
โstation_id ๊ธฐ์ค์ผ๋ก GROUP BY
โ๋์ฌ/๋ฐ๋ฉ๊ฑด์ ๋น์จ ๊ตฌํ๊ณ HAVING ์ ๋ก 2์ฐจ ํํฐ๋ง