You have two tables: Contacts and Calls. The Contacts table stores contact information with id, first_name, and last_name. The Calls table stores call records with contact_id (foreign key to Contacts), type (incoming/outgoing), and duration in seconds.
Your task: Find the three longest calls for each call type (incoming and outgoing). Return results ordered by type, duration, and first_name in descending order. The duration must be formatted as HH:MM:SS.
- For each call type, return only the top 3 longest calls
- Format duration from seconds to
HH:MM:SSformat - Order by type DESC, duration DESC, first_name DESC
Table Schema
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key, unique contact identifier |
first_name
|
varchar | Contact's first name |
last_name
|
varchar | Contact's last name |
| Column Name | Type | Description |
|---|---|---|
contact_id
PK
|
int | Foreign key referencing Contacts.id |
type
PK
|
enum | Call type: 'incoming' or 'outgoing' |
duration
PK
|
int | Call duration in seconds |
Input & Output
| id | first_name | last_name |
|---|---|---|
| 1 | John | Doe |
| 2 | Jane | Smith |
| 3 | Alice | Johnson |
| 4 | Bob | Brown |
| contact_id | type | duration |
|---|---|---|
| 1 | outgoing | 1800 |
| 2 | incoming | 1500 |
| 3 | outgoing | 1200 |
| 4 | incoming | 900 |
| 1 | incoming | 2100 |
| 2 | outgoing | 1600 |
| first_name | last_name | type | duration |
|---|---|---|---|
| John | Doe | outgoing | 00:30:00 |
| Jane | Smith | outgoing | 00:26:40 |
| Alice | Johnson | outgoing | 00:20:00 |
| John | Doe | incoming | 00:35:00 |
| Jane | Smith | incoming | 00:25:00 |
| Bob | Brown | incoming | 00:15:00 |
The query finds the top 3 longest calls for each type. For outgoing calls: John (1800s), Jane (1600s), Alice (1200s). For incoming calls: John (2100s), Jane (1500s), Bob (900s). Results are ordered by type DESC, duration DESC, first_name DESC.
| id | first_name | last_name |
|---|---|---|
| 1 | Tom | Wilson |
| 2 | Sara | Davis |
| contact_id | type | duration |
|---|---|---|
| 1 | outgoing | 3600 |
| 2 | incoming | 1800 |
| 1 | incoming | 1200 |
| first_name | last_name | type | duration |
|---|---|---|---|
| Tom | Wilson | outgoing | 01:00:00 |
| Sara | Davis | incoming | 00:30:00 |
| Tom | Wilson | incoming | 00:20:00 |
When there are fewer than 3 calls for a type, all available calls are returned. Here we have only 1 outgoing call and 2 incoming calls, so all 3 records are included in the result.
Constraints
-
1 ≤ contact_id ≤ 1000 -
typeis either'incoming'or'outgoing' -
1 ≤ duration ≤ 86400(max 24 hours) - Each contact can have multiple calls of different types