-
Notifications
You must be signed in to change notification settings - Fork 2
/
14.sql
128 lines (124 loc) · 3.36 KB
/
14.sql
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
-- [ 프로그래머스 ] 특정 기간동안 대여 가능한 자동차들의 대여비용 구하기
SELECT
CAR_ID,
CAR_TYPE,
FEE
FROM (
SELECT
TARGET_CARS.CAR_ID,
TARGET_CARS.CAR_TYPE,
ROUND(TARGET_CARS.DAILY_FEE * ((100 - TARGET_DISCOUNT.DISCOUNT_RATE) / 100) * 30, 0) AS FEE
FROM (
SELECT
TARGET_CARS.CAR_ID,
TARGET_CARS.CAR_TYPE,
TARGET_CARS.DAILY_FEE
FROM (
SELECT
CAR_ID,
CAR_TYPE,
DAILY_FEE
FROM CAR_RENTAL_COMPANY_CAR
WHERE (
CAR_TYPE = '세단'
OR
CAR_TYPE = 'SUV'
)
) AS TARGET_CARS
LEFT JOIN (
SELECT CAR_ID
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE (
(
START_DATE <= '2022-11-01'
AND
END_DATE >= '2022-11-01'
)
OR
(
START_DATE >= '2022-11-01'
AND
END_DATE <= '2022-11-30'
)
)
) AS NONE_TARGET_CARS
USING (CAR_ID)
WHERE NONE_TARGET_CARS.CAR_ID IS NULL
) TARGET_CARS
JOIN (
SELECT
CAR_TYPE,
DISCOUNT_RATE
FROM CAR_RENTAL_COMPANY_DISCOUNT_PLAN
WHERE (
(
CAR_TYPE = '세단'
OR
CAR_TYPE = 'SUV'
)
AND
DURATION_TYPE = '30일 이상'
)
) AS TARGET_DISCOUNT
USING (CAR_TYPE)
) AS RESULT
WHERE (
FEE >= 500000
AND
FEE < 2000000
)
ORDER BY FEE DESC, CAR_TYPE ASC, CAR_ID DESC;
/*
아래와 같이 GROUP BY 구 및 HAVING 구, 그리고 MAX 집계 함수를 사용하여 문제를 풀 수도 있다.
IF 함수를 사용해 해당 기간 내에 빌리지 못하는 경우에 대해 값을 1로 치환하는 방식이다.
*/
SELECT
CAR_ID,
CAR_TYPE,
FEE
FROM (
SELECT
CAR_RENTAL_COMPANY_CAR.CAR_ID,
CAR_RENTAL_COMPANY_CAR.CAR_TYPE,
ROUND(CAR_RENTAL_COMPANY_CAR.DAILY_FEE * ((100 - CAR_RENTAL_COMPANY_DISCOUNT_PLAN.DISCOUNT_RATE) / 100) * 30, 0) AS FEE
FROM CAR_RENTAL_COMPANY_CAR
JOIN CAR_RENTAL_COMPANY_RENTAL_HISTORY
USING (CAR_ID)
JOIN CAR_RENTAL_COMPANY_DISCOUNT_PLAN
USING (CAR_TYPE)
WHERE (
(
CAR_RENTAL_COMPANY_CAR.CAR_TYPE = '세단'
OR
CAR_RENTAL_COMPANY_CAR.CAR_TYPE = 'SUV'
)
AND
CAR_RENTAL_COMPANY_DISCOUNT_PLAN.DURATION_TYPE = '30일 이상'
)
GROUP BY CAR_RENTAL_COMPANY_CAR.CAR_ID
HAVING MAX(
IF(
(
(
CAR_RENTAL_COMPANY_RENTAL_HISTORY.START_DATE <= '2022-11-01'
AND
CAR_RENTAL_COMPANY_RENTAL_HISTORY.END_DATE >= '2022-11-01'
)
OR
(
CAR_RENTAL_COMPANY_RENTAL_HISTORY.START_DATE >= '2022-11-01'
AND
CAR_RENTAL_COMPANY_RENTAL_HISTORY.END_DATE <= '2022-11-30'
)
),
1,
0
)
) = 0
) AS TARGET_CARS
WHERE (
FEE >= 500000
AND
FEE <= 2000000
)
ORDER BY FEE DESC, CAR_TYPE ASC, CAR_ID DESC;