A network monitoring system writes one log row per traffic measurement, tagged with the protocol it belongs to. Calculate the average traffic_volume per protocol, rounded to 2 decimal places. Return protocol_name and avg_traffic, sorted by avg_traffic descending, with ties broken by protocol_id ascending.
Input Table(s)
Protocols
| Column | Type | Meaning |
|---|
| protocol_id | INT | Protocol id. Primary key. |
| protocol_name | VARCHAR(50) | Protocol name, such as HTTP. NOT NULL. |
Logs
| Column | Type | Meaning |
|---|
| log_id | INT | Log entry id. Primary key. |
| protocol_id | INT | Protocol of the measurement. Foreign key to Protocols.protocol_id. |
| traffic_volume | DECIMAL(12,2) | Measured traffic volume. NOT NULL. |
| log_timestamp | TIMESTAMP | When the measurement was taken. NOT NULL. |
Keys: Protocols.protocol_id and Logs.log_id are primary keys. Logs.protocol_id references Protocols.protocol_id.
Output Contract
-
Columns, in this order:
protocol_name
,
avg_traffic
.
-
One row per protocol that has at least one log entry.
-
avg_traffic
is the mean of that protocol's
traffic_volume
values, rounded to 2 decimal places (half away from zero, as PostgreSQL's
ROUND
on a numeric does).
-
Order by the rounded
avg_traffic
descending, then
protocol_id
ascending.
protocol_id
is unique, so the order is fully determined.
Example
Protocols
| protocol_id | protocol_name |
|---|
| 1 | HTTP |
| 2 | HTTPS |
| 3 | SSH |
| 4 | FTP |
| 5 | DNS |
Logs
| log_id | protocol_id | traffic_volume | log_timestamp |
|---|
| 1 | 1 | 120.50 | 2024-06-01 08:00:00 |
| 2 | 2 | 300.25 | 2024-06-01 08:05:00 |
| 3 | 3 | 15.10 | 2024-06-01 08:10:00 |
| 4 | 1 | 80.00 | 2024-06-01 09:00:00 |
| 5 | 2 | 199.75 | 2024-06-01 09:30:00 |
| 6 | 5 | 250.00 | 2024-06-01 10:00:00 |
| 7 | 3 | 15.20 | 2024-06-01 10:15:00 |
| 8 | 2 | 250.00 | 2024-06-01 11:00:00 |
| 9 | 1 | 100.00 | 2024-06-01 11:30:00 |
| 10 | 3 | 15.25 | 2024-06-01 12:00:00 |
Expected output:
| protocol_name | avg_traffic |
|---|
| HTTPS | 250.00 |
| DNS | 250.00 |
| HTTP | 100.17 |
| SSH | 15.18 |
HTTPS averages 750.00 / 3 = 250.00 and DNS has a single 250.00 entry, so they tie and HTTPS (id 2) comes before DNS (id 5). HTTP averages 300.50 / 3 = 100.1667, which rounds to 100.17, and SSH averages 45.55 / 3 = 15.1833, which rounds to 15.18. FTP has no log entries and produces no row.
Constraints and Clarifications
-
Protocols
has at most 100 rows and
Logs
at most 10,000.
-
traffic_volume
is a non-negative decimal value.
-
Every log entry references a valid
protocol_id
in
Protocols
, so no log row has a NULL or unknown protocol.
-
Protocols with no log entries are left out of the result.
-
Two protocols may share a name; they are still reported as separate rows.