Skip to content

Commit c9a48a2

Browse files
authored
Create calculate-parking-fees-and-duration.sql
1 parent 80850b6 commit c9a48a2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
WITH info_cte AS (
5+
SELECT car_id,
6+
lot_id,
7+
SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) AS duration
8+
FROM ParkingTransactions
9+
GROUP BY 1, 2
10+
ORDER BY NULL
11+
), max_info_cte AS (
12+
SELECT car_id,
13+
MAX(duration) AS max_duration
14+
FROM info_cte
15+
GROUP BY 1
16+
ORDER BY NULL
17+
), max_duration_lot_cte AS (
18+
SELECT a.car_id,
19+
lot_id AS most_time_lot
20+
FROM info_cte a INNER JOIN max_info_cte b
21+
ON a.car_id = b.car_id AND a.duration = b.max_duration
22+
), total_cte AS (
23+
SELECT car_id,
24+
SUM(fee_paid) AS total_fee_paid,
25+
SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) AS total_duration
26+
FROM ParkingTransactions
27+
GROUP BY 1
28+
ORDER BY NULL
29+
)
30+
31+
SELECT a.car_id,
32+
total_fee_paid,
33+
ROUND(total_fee_paid * 3600 / total_duration, 2) AS avg_hourly_fee,
34+
most_time_lot
35+
FROM max_duration_lot_cte a INNER JOIN total_cte b
36+
ON a.car_id = b.car_id
37+
ORDER BY 1;

0 commit comments

Comments
 (0)