Post

[Programmers] 자동차 대여 기록 별 대여 금액 구하기 - 151141

[Programmers] 자동차 대여 기록 별 대여 금액 구하기 - 151141

문제

자동차 대여 기록 별 대여 금액 구하기

풀이

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-- # -- 코드를 입력하세요
-- # SELECT *
-- # FROM (SELECT car_id, daily_fee
-- #      FROM car_rental_company_car
-- #      WHERE car_type = '트럭') AS truck
-- #      JOIN
-- #      (SELECT history_id, car_id, (end_date - start_date) AS duration
-- #      FROM car_rental_company_rental_history) AS history
-- #      ON truck.car_id = history.car_id
-- #      JOIN
-- #      (SELECT duration_type, discount_rate
-- #      FROM car_rental_company_discount_plan
-- #      WHERE car_type = '트럭') AS truck_discount
-- #      ON
-- #         CASE
-- #             WHEN history.duration >= 7 THEN (SELECT discount_rate
-- #                                              FROM truck_discount
-- #                                              WHERE duration_type = '7일 이상')
-- #             WHEN history.duration >= 30 THEN (SELECT discount_rate
-- #                                              FROM truck_discount
-- #                                              WHERE duration_type = '30일 이상')
-- #             WHEN history.duration >= 90 THEN (SELECT discount_rate
-- #                                              FROM truck_discount
-- #                                              WHERE duration_type = '90일 이상')
-- #             ELSE 0

WITH value AS (
    SELECT car.daily_fee, car.car_type, his.history_id,
           DATEDIFF(end_date, start_date) + 1 AS period,
    CASE 
      WHEN DATEDIFF(end_date, start_date) + 1 >= 90 THEN '90일 이상'
      WHEN DATEDIFF(end_date, start_date) + 1 >= 30 THEN '30일 이상'
      WHEN DATEDIFF(end_date, start_date) + 1 >= 7 THEN '7일 이상'
      ELSE 'NONE' END AS duration_type
FROM car_rental_company_rental_history AS his
INNER JOIN car_rental_company_car AS car ON car.car_id = his.car_id
WHERE car.car_type = '트럭')   



SELECT value.history_id, 
    ROUND(value.daily_fee * value.period * 
          (100 - IFNULL(plan.discount_rate,0)) / 100) AS FEE
FROM value
LEFT JOIN car_rental_company_discount_plan AS plan 
    ON plan.duration_type = value.duration_type 
    AND plan.car_type = value.car_type
ORDER BY 2 DESC, 1 DESC

설명

이 문제는 SQL을 활용한 데이터 조회 문제다.

접근 방법

문제의 요구사항을 분석하여 적절한 SQL 쿼리를 작성했다.

주요 포인트

  • 필요한 테이블 JOIN
  • WHERE 조건절을 통한 데이터 필터링
  • ORDER BY를 통한 정렬

시간 복잡도

데이터베이스 인덱스와 쿼리 최적화에 따라 성능이 결정된다.

This post is licensed under CC BY 4.0 by the author.