๐Ÿ’ SQL (Programmers)/String, Date

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ์ž๋™์ฐจ ๋Œ€์—ฌ ๊ธฐ๋ก ๋ณ„ ๋Œ€์—ฌ ๊ธˆ์•ก ๊ตฌํ•˜๊ธฐ

์„ ๋‹ฌ 2023. 8. 14. 16:10
๋ฐ˜์‘ํ˜•

https://school.programmers.co.kr/learn/courses/30/lessons/151141

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๋ฌธ์ œ

CAR_RENTAL_COMPANY_CAR ํ…Œ์ด๋ธ”๊ณผ CAR_RENTAL_COMPANY_RENTAL_HISTORY ํ…Œ์ด๋ธ”๊ณผ CAR_RENTAL_COMPANY_DISCOUNT_PLAN ํ…Œ์ด๋ธ”์—์„œ 

์ž๋™์ฐจ ์ข…๋ฅ˜๊ฐ€ 'ํŠธ๋Ÿญ'์ธ ์ž๋™์ฐจ์˜ ๋Œ€์—ฌ ๊ธฐ๋ก์— ๋Œ€ํ•ด์„œ 

๋Œ€์—ฌ ๊ธฐ๋ก ๋ณ„๋กœ ๋Œ€์—ฌ ๊ธˆ์•ก(์ปฌ๋Ÿผ๋ช…: FEE)์„ ๊ตฌํ•˜์—ฌ 

๋Œ€์—ฌ ๊ธฐ๋ก ID์™€ ๋Œ€์—ฌ ๊ธˆ์•ก ๋ฆฌ์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. 

๊ฒฐ๊ณผ๋Š” ๋Œ€์—ฌ ๊ธˆ์•ก์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ณ , ๋Œ€์—ฌ ๊ธˆ์•ก์ด ๊ฐ™์€ ๊ฒฝ์šฐ ๋Œ€์—ฌ ๊ธฐ๋ก ID๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

ํ’€์ด

1. car ์™€ history ํ…Œ์ด๋ธ”์„ inner join

 

2. plan ํ…Œ์ด๋ธ”๊ณผ left join

-> history ํ…Œ์ด๋ธ”์—์„œ start date ์™€ end date ์‚ฌ์ด์˜ ๋‚ ์งœ๋ฅผ datediff ๋กœ ์—ฐ์‚ฐํ•˜์—ฌ ๋Œ€์—ฌ๊ธฐ๊ฐ„์„ ๊ตฌํ•˜๊ณ  case when์„ ์ด์šฉํ•˜์—ฌ์ด ๋Œ€์—ฌ๊ธฐ๊ฐ„์— ๋”ฐ๋ผ duration_type ๊ณผ ๋งค์นญํ•˜์—ฌ join ํ•˜๋ฉด ๊ฐ ๋Œ€์—ฌ๊ธฐ๊ฐ„์— ๋งž๋Š” ํ• ์ธ์œจ์ด ์นผ๋Ÿผ์œผ๋กœ ๋“ค์–ด๊ฐ„๋‹ค

 

์ด๋•Œ ๋‚ ์งœ๋ฅผ +1 ํ•˜๋Š”๊ฑฐ์— ์ฃผ์˜ํ•˜์ž,

์˜ˆ์ œ๋ฅผ ๋ณด๋ฉด start date: 08-03, end date: 08-04์˜ ๋Œ€์—ฌ๊ธฐ๊ฐ„์„ 2์ผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค

์–‘์•„์น˜

 

3. ์š”๊ธˆ์„ ๊ณ„์‚ฐํ•˜์—ฌ fee ์นผ๋Ÿผ์— ๋„ฃ๋Š”๋‹ค

fee = ๊ธฐ๊ฐ„ * daily_fee * ํ• ์ธ์œจ

ํ• ์ธ์œจ = (100 - discount_rate) / 100

-> ๋งŒ์•ฝ ๋Œ€์—ฌ๊ธฐ๊ฐ„์ด 7์ผ ๋ฏธ๋งŒ์ด๋ผ๋ฉด ๋งค์นญ๋œ ํ• ์ธ ํ”Œ๋žœ์ด ์—†๊ฒŒ๋˜๊ณ  p.discount_rate ๋Š” null ๊ฐ’์„ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค. ์ด ๊ฒฝ์šฐ discount_rate๋Š” 0์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค

๊ทธ๋ฆฌ๊ณ  ์ตœ์ข…์œผ๋กœ ๋‚˜์˜จ fee๋Š” ์†Œ์ˆ˜์ ์ด ํฌํ•จ๋˜์–ด์žˆ๊ธฐ์— floor ๋กœ ๋‚ด๋ฆผ ์—ฐ์‚ฐ์„ ํ•ด์ค€๋‹ค

 

4. where ์„ ์ด์šฉํ•˜์—ฌ ์กฐ๊ฑด ๊ฑธ๊ณ  order by ์ด์šฉํ•˜์—ฌ ์ˆœ์„œ ์กฐ๊ฑด ๋งž์ถฐ์ฃผ๋ฉด ๋

 

select h.history_id, 
    floor((datediff(h.end_date, h.start_date)+1) * c.daily_fee * (100-ifnull(p.discount_rate, 0))/100) as fee
from car_rental_company_car c
    join car_rental_company_rental_history h on c.car_id = h.car_id
    left join car_rental_company_discount_plan p on c.car_type = p.car_type and p.duration_type =
        case when datediff(h.end_date, h.start_date)+1 between 7 and 29 then "7์ผ ์ด์ƒ"
        when datediff(h.end_date, h.start_date)+1 between 30 and 89 then "30์ผ ์ด์ƒ"
        when datediff(h.end_date, h.start_date)+1 >= 90 then "90์ผ ์ด์ƒ" end
where c.car_type = 'ํŠธ๋Ÿญ'
order by fee desc, h.history_id desc
๋ฐ˜์‘ํ˜•