Server Utilization Time - Problem
You are working as a DevOps engineer for a cloud hosting company that needs to calculate billing based on server usage. Your task is to analyze server activity logs to determine the total time servers were actively running.
Given a database table Servers that logs every time a server starts or stops, you need to calculate the total uptime across all servers and convert it to full days (rounded down).
Key Requirements:
- Each server can have multiple start/stop sessions
- Sessions are properly paired (every start has a corresponding stop)
- Calculate total runtime across ALL servers
- Return result as full days only (floor the result)
Example: If servers ran for 25.7 hours total, that equals 1.07 days, which rounds down to 1 full day.
Input & Output
example_1.sql โ Basic Server Sessions
$
Input:
Servers table with multiple server sessions:
server_id=1: start at 03:05:31, stop at 11:10:31 (8 hours)
server_id=3: start at 16:29:47, stop at 01:49:47 next day (9.3 hours)
โบ
Output:
total_uptime_days: 0
๐ก Note:
Total runtime is 17.3 hours, which equals 0.72 days. Since we floor the result, it becomes 0 full days.
example_2.sql โ Extended Sessions
$
Input:
Multiple servers with longer sessions:
server_id=1: 8 + 1.2 = 9.2 hours
server_id=3: 9.3 + 2.2 + 2.0 = 13.5 hours
server_id=4: 6.5 + 0.5 + 5.7 + 7.8 = 20.5 hours
server_id=5: 1.4 hours
โบ
Output:
total_uptime_days: 1
๐ก Note:
Total runtime is 44.6 hours = 1.86 days. Floored to 1 full day.
example_3.sql โ Edge Case - Short Sessions
$
Input:
Multiple very short server sessions:
server_id=1: 0.5 hours
server_id=2: 1.0 hours
server_id=3: 0.3 hours
โบ
Output:
total_uptime_days: 0
๐ก Note:
Total runtime is 1.8 hours = 0.075 days. Floored to 0 full days.
Constraints
- 1 โค number of server records โค 104
- Each server has properly paired start/stop events
- status_time is a valid datetime format
- session_status is either 'start' or 'stop'
- No overlapping sessions for the same server
- All timestamps are in chronological order per server
Visualization
Tap to expand
Understanding the Visualization
1
Group by Server
Separate all events by server_id, like sorting parking tickets by license plate
2
Sequence Events
Number start and stop events chronologically for each server
3
Pair Sessions
Match start event #1 with stop event #1, start #2 with stop #2, etc.
4
Calculate Duration
Compute time difference for each session pair
5
Aggregate & Convert
Sum all durations and convert to full days using FLOOR function
Key Takeaway
๐ฏ Key Insight: Window functions enable efficient session pairing by partitioning data by server and sequencing events chronologically, avoiding expensive nested queries while maintaining optimal performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code