3118. Friday Purchase III
Medium
Topics
SQL Schema
Pandas Schema
Table: Purchases
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user_id, purchase_date, and amount_spend.
Table: Users
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| membership | enum |
+-------------+------+
user_id is the primary key for this table.
membership is an ENUM (category) type of ('Standard', 'Premium', 'VIP').
Each row of this table indicates the user_id, membership type.
Write a solution to calculate the total spending by Premium and VIP members on each Friday of every week in November 2023. If there are no purchases on a particular Friday by Premium or VIP members, it should be considered as 0.
Return the result table ordered by week of the month, and membership in ascending order.
During the first week of November 2023, a transaction occurred on Friday, 2023-11-03, by a Premium member amounting to $1,126. No transactions were made by VIP members on this day, resulting in a value of 0.
For the second week of November 2023, there was a transaction on Friday, 2023-11-10, and it was made by a VIP member, amounting to $7,473. Since there were no purchases by Premium members that Friday, the output shows 0 for Premium members.
Similarly, during the third week of November 2023, no transactions by Premium or VIP members occurred on Friday, 2023-11-17, which shows 0 for both categories in this week.
In the fourth week of November 2023, transactions occurred on Friday, 2023-11-24, involving one Premium member purchase of $5,117 and VIP member purchases totaling $14,933 ($9,692 from one and $5,241 from another).
Note: The output table is ordered by week_of_month and membership in ascending order.
# Write your MySQL query statement below
SELECT
f.week_of_month,
m.membership,
COALESCE(SUM(p.amount_spend), 0) AS total_amount
FROM (
SELECT 1 AS week_of_month, DATE '2023-11-03' AS fri
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| first_name | varchar |
| last_name | varchar |
+-------------+---------+
id is the primary key (column with unique values) of this table.
id is a foreign key (reference column) to Calls table.
Each row of this table contains id, first_name, and last_name.
Table: Calls
+-------------+------+
| Column Name | Type |
+-------------+------+
| contact_id | int |
| type | enum |
| duration | int |
+-------------+------+
(contact_id, type, duration) is the primary key (column with unique values) of this table.
type is an ENUM (category) type of ('incoming', 'outgoing').
Each row of this table contains information about calls, comprising of contact_id, type, and duration in seconds.
Write a solution to find the three longest incoming and outgoing calls.
Return the result table ordered by type, duration, and first_name in descending order and duration must be formatted as HH:MM:SS.
The result format is in the following example.
Example 1:
Input:
Contacts table:
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | John | Doe |
| 2 | Jane | Smith |
| 3 | Alice | Johnson |
| 4 | Michael | Brown |
| 5 | Emily | Davis |
+----+------------+-----------+
Calls table:
+-----------+----------+-------------------+
| first_name| type | duration_formatted|
+-----------+----------+-------------------+
| Alice | outgoing | 00:06:00 |
| Emily | outgoing | 00:04:40 |
| Jane | outgoing | 00:04:00 |
| Michael | incoming | 00:07:00 |
| Jane | incoming | 00:05:00 |
| Emily | incoming | 00:03:00 |
+-----------+----------+-------------------+
Explanation:
Alice had an outgoing call lasting 6 minutes.
Emily had an outgoing call lasting 4 minutes and 40 seconds.
Jane had an outgoing call lasting 4 minutes.
Michael had an incoming call lasting 7 minutes.
Jane had an incoming call lasting 5 minutes.
Emily had an incoming call lasting 3 minutes.
Note: Output table is sorted by type, duration, and first_name in descending order.
# Write your MySQL query statement below
WITH ranked AS (
SELECT
c.first_name,
ca.type,
ca.duration,
ROW_NUMBER() OVER (
PARTITION BY ca.type
ORDER BY ca.duration DESC
) AS rn
FROM Calls ca
JOIN Contacts c
ON c.id = ca.contact_id
)
SELECT
first_name,
type,
TIME_FORMAT(SEC_TO_TIME(duration), '%H:%i:%s') AS duration_formatted
FROM ranked
WHERE rn <= 3
ORDER BY type DESC, duration DESC, first_name DESC;
3126. Server Utilization Time
Medium
Topics
SQL Schema
Pandas Schema
Table: Servers
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| server_id | int |
| status_time | datetime |
| session_status | enum |
+----------------+----------+
(server_id, status_time, session_status) is the primary key (combination of columns with unique values) for this table.
session_status is an ENUM (category) type of ('start', 'stop').
Each row of this table contains server_id, status_time, and session_status.
Write a solution to find the total time when servers were running. The output should be rounded down to the nearest number of full days.
For server ID 3:
From 2023-11-04 16:29:47 to 2023-11-05 01:49:47: ~9.3 hours
From 2023-11-25 01:37:08 to 2023-11-25 03:50:08: ~2.2 hours
From 2023-11-04 23:16:48 to 2023-11-05 01:15:48: ~1.98 hours
Total for server 3: ~13.48 hours
For server ID 1:
From 2023-11-13 03:05:31 to 2023-11-13 11:10:31: ~8 hours
From 2023-11-20 00:27:11 to 2023-11-20 01:41:11: ~1.23 hours
Total for server 1: ~9.23 hours
For server ID 4:
From 2023-11-29 15:11:17 to 2023-11-29 15:42:17: ~0.52 hours
From 2023-11-20 00:31:44 to 2023-11-20 07:03:44: ~6.53 hours
From 2023-11-30 15:09:18 to 2023-11-30 20:48:18: ~5.65 hours
From 2023-11-25 21:09:06 to 2023-11-26 04:58:06: ~7.82 hours
Total for server 4: ~20.52 hours
For server ID 5:
From 2023-11-16 19:42:22 to 2023-11-16 21:08:22: ~1.43 hours
Total for server 5: ~1.43 hours
The accumulated runtime for all servers totals approximately 44.46 hours, equivalent to one full day plus some additional hours. However, since we consider only full days, the final output is rounded to 1 full day.
# Write your MySQL query statement below
SELECT
FLOOR(
SUM(
CASE
WHEN session_status = 'stop'
THEN TIMESTAMPDIFF(SECOND, '2023-11-01', status_time)
3140. Consecutive Available Seats II
Medium
Topics
SQL Schema
Pandas Schema
Table: Cinema
+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id | int |
| free | bool |
+-------------+------+
seat_id is an auto-increment column for this table.
Each row of this table indicates whether the ith seat is free or not. 1 means free while 0 means occupied.
Write a solution to find the length of longest consecutive sequence of available seats in the cinema.
Note:
There will always be at most one longest consecutive sequence.
If there are multiple consecutive sequences with the same length, include all of them in the output.
Return the result table ordered by first_seat_id in ascending order.
Longest consecutive sequence of available seats starts from seat 3 and ends at seat 5 with a length of 3.
Output table is ordered by first_seat_id in ascending order.
# Write your MySQL query statement below
WITH islands AS (
SELECT
seat_id,
seat_id - ROW_NUMBER() OVER (ORDER BY seat_id) AS grp
FROM Cinema
WHERE free = 1
),
runs AS (
SELECT
MIN(seat_id) AS first_seat_id,
MAX(seat_id) AS last_seat_id,
COUNT(*) AS consecutive_seats_len
FROM islands
GROUP BY grp
)
SELECT
first_seat_id,
last_seat_id,
consecutive_seats_len
FROM runs
WHERE consecutive_seats_len = (SELECT MAX(consecutive_seats_len) FROM runs)
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.
Write a solution to find invalid tweets. A tweet is considered invalid if it meets any of the following criteria:
It exceeds 140 characters in length.
It has more than 3 mentions.
It includes more than 3 hashtags.
Return the result table ordered by tweet_id in ascending order.
The result format is in the following example.
Example:
Input:
Tweets table:
+----------+-----------------------------------------------------------------------------------+
| tweet_id | content |
+----------+-----------------------------------------------------------------------------------+
| 1 | Traveling, exploring, and living my best life @janesmith @SaraJohnson @LisaTaylor |
| | @MikeBrown #Foodie #Fitness #Learning |
| 2 | Just had the best dinner with friends! #Foodie #Friends #Fun |
| 4 | Working hard on my new project #Work #Goals #Productivity #Fun |
+----------+-----------------------------------------------------------------------------------+
3156. Employee Task Duration and Concurrent Tasks
Hard
Topics
SQL Schema
Pandas Schema
Table: Tasks
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| task_id | int |
| employee_id | int |
| start_time | datetime |
| end_time | datetime |
+---------------+----------+
(task_id, employee_id) is the primary key for this table.
Each row in this table contains the task identifier, the employee identifier, and the start and end times of each task.
Write a solution to find the total duration of tasks for each employee and the maximum number of concurrent tasks an employee handled at any point in time. The total duration should be rounded down to the nearest number of full hours.
Return the result table ordered by employee_id ascending order.
For employee ID 1001:
Task 1 and Task 2 overlap from 08:30 to 09:00 (30 minutes).
Task 7 has a duration of 150 minutes (2 hours and 30 minutes).
Total task time: 60 (Task 1) + 120 (Task 2) + 60 (Task 3) + 150 (Task 7) - 30 (overlap) = 360 minutes = 6 hours.
Maximum concurrent tasks: 2 (during the overlap period).
For employee ID 1002:
Task 4 and Task 5 overlap from 09:30 to 10:00 (30 minutes).
Total task time: 60 (Task 4) + 120 (Task 5) - 30 (overlap) = 150 minutes = 2 hours and 30 minutes.
Total task hours (rounded down): 2 hours.
Maximum concurrent tasks: 2 (during the overlap period).
For employee ID 1003:
No overlapping tasks.
Total task time: 120 minutes = 2 hours.
Maximum concurrent tasks: 1.
Note: Output table is ordered by employee_id in ascending order.
# Write your MySQL query statement below
WITH ordered AS (
SELECT
employee_id,
task_id,
start_time,
end_time,
MAX(end_time) OVER (
PARTITION BY employee_id
ORDER BY start_time, end_time, task_id
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS prev_max_end
FROM Tasks
),
flagged AS (
SELECT
employee_id,
start_time,
end_time,
SUM(CASE
WHEN prev_max_end IS NULL OR start_time > prev_max_end THEN 1
ELSE 0
END) OVER (
PARTITION BY employee_id
ORDER BY start_time, end_time, task_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS grp
FROM ordered
),
merged AS (
SELECT
employee_id,
TIMESTAMPDIFF(SECOND, MIN(start_time), MAX(end_time)) AS secs
FROM flagged
GROUP BY employee_id, grp
),
total AS (
SELECT
employee_id,
FLOOR(SUM(secs) / 3600) AS total_task_hours
FROM merged
GROUP BY employee_id
),
concurrency AS (
SELECT
a.employee_id,
a.task_id,
COUNT(*) AS cnt
FROM Tasks a
JOIN Tasks b
ON b.employee_id = a.employee_id
AND b.start_time <= a.start_time
AND b.end_time > a.start_time
GROUP BY a.employee_id, a.task_id
),
max_conc AS (
SELECT employee_id, MAX(cnt) AS max_concurrent_tasks
3166. Calculate Parking Fees and Duration
Medium
Topics
SQL Schema
Pandas Schema
Table: ParkingTransactions
+--------------+-----------+
| Column Name | Type |
+--------------+-----------+
| lot_id | int |
| car_id | int |
| entry_time | datetime |
| exit_time | datetime |
| fee_paid | decimal |
+--------------+-----------+
(lot_id, car_id, entry_time) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the ID of the parking lot, the ID of the car, the entry and exit times, and the fee paid for the parking duration.
Write a solution to find the total parking fee paid by each car across all parking lots, and the average hourly fee (rounded to 2 decimal places) paid by each car. Also, find the parking lot where each car spent the most total time.
Return the result table ordered by car_id in ascending order.
Note: Test cases are generated in such a way that an individual car cannot be in multiple parking lots at the same time.
For car ID 1001:
From 2023-06-01 08:00:00 to 2023-06-01 10:30:00 in lot 1: 2.5 hours, fee 5.00
From 2023-06-02 11:00:00 to 2023-06-02 12:45:00 in lot 1: 1.75 hours, fee 3.00
From 2023-06-01 10:45:00 to 2023-06-01 12:00:00 in lot 2: 1.25 hours, fee 6.00
From 2023-06-03 07:00:00 to 2023-06-03 09:00:00 in lot 3: 2 hours, fee 4.00
Total fee paid: 18.00, total hours: 7.5, average hourly fee: 2.40, most time spent in lot 1: 4.25 hours.
For car ID 1002:
From 2023-06-01 09:00:00 to 2023-06-01 11:30:00 in lot 2: 2.5 hours, fee 4.00
From 2023-06-02 12:00:00 to 2023-06-02 14:00:00 in lot 3: 2 hours, fee 2.00
Total fee paid: 6.00, total hours: 4.5, average hourly fee: 1.33, most time spent in lot 2: 2.5 hours.
Note: Output table is ordered by car_id in ascending order.
# Write your MySQL query statement below
WITH lot_time AS (
SELECT
car_id,
lot_id,
SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) AS lot_secs
FROM ParkingTransactions
GROUP BY car_id, lot_id
),
ranked AS (
SELECT
car_id,
lot_id,
ROW_NUMBER() OVER (
PARTITION BY car_id
ORDER BY lot_secs DESC, lot_id
) AS rn
FROM lot_time
),
totals AS (
SELECT
car_id,
SUM(fee_paid) AS total_fee_paid,
SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) AS total_secs
FROM ParkingTransactions
GROUP BY car_id
)
SELECT
t.car_id,
t.total_fee_paid,
ROUND(t.total_fee_paid / (t.total_secs / 3600), 2) AS avg_hourly_fee,
3172. Second Day Verification
Easy
Topics
SQL Schema
Pandas Schema
Table: emails
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| email_id | int |
| user_id | int |
| signup_date | datetime |
+-------------+----------+
(email_id, user_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the email ID, user ID, and signup date.
Table: texts
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| text_id | int |
| email_id | int |
| signup_action | enum |
| action_date | datetime |
+---------------+----------+
(text_id, email_id) is the primary key (combination of columns with unique values) for this table.
signup_action is an enum type of ('Verified', 'Not Verified').
Each row of this table contains the text ID, email ID, signup action, and action date.
Write a Solution to find the user IDs of those who verified their sign-up on the second day.
Return the result table ordered by user_id in ascending order.
User with user_id 7005 and email_id 234 signed up on 2022-08-20 10:00:00 and verified on second day of the signup.
User with user_id 7771 and email_id 125 signed up on 2022-06-14 09:30:00 and verified on second day of the signup.
3182. Find Top Scoring Students
Medium
Topics
SQL Schema
Pandas Schema
Table: students
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| name | varchar |
| major | varchar |
+-------------+----------+
student_id is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the student ID, student name, and their major.
Table: courses
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| course_id | int |
| name | varchar |
| credits | int |
| major | varchar |
+-------------+----------+
course_id is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the course ID, course name, the number of credits for the course, and the major it belongs to.
Table: enrollments
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| course_id | int |
| semester | varchar |
| grade | varchar |
+-------------+----------+
(student_id, course_id, semester) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the student ID, course ID, semester, and grade received.
Write a solution to find the students who have taken all courses offered in their major and have achieved a grade of A in all these courses.
Return the result table ordered by student_id in ascending order.
The result format is in the following example.
Example:
Input:
students table:
+------------+------------------+------------------+
| student_id | name | major |
+------------+------------------+------------------+
| 1 | Alice | Computer Science |
| 2 | Bob | Computer Science |
| 3 | Charlie | Mathematics |
| 4 | David | Mathematics |
+------------+------------------+------------------+
courses table:
Alice (student_id 1) is a Computer Science major and has taken both "Algorithms" and "Data Structures", receiving an 'A' in both.
Bob (student_id 2) is a Computer Science major but did not receive an 'A' in all required courses.
Charlie (student_id 3) is a Mathematics major and has taken both "Calculus" and "Linear Algebra", receiving an 'A' in both.
David (student_id 4) is a Mathematics major but did not receive an 'A' in all required courses.
Note: Output table is ordered by student_id in ascending order.
3188. Find Top Scoring Students II
Hard
Topics
SQL Schema
Pandas Schema
Table: students
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| name | varchar |
| major | varchar |
+-------------+----------+
student_id is the primary key for this table.
Each row contains the student ID, student name, and their major.
Table: courses
+-------------+-------------------+
| Column Name | Type |
+-------------+-------------------+
| course_id | int |
| name | varchar |
| credits | int |
| major | varchar |
| mandatory | enum |
+-------------+-------------------+
course_id is the primary key for this table.
mandatory is an enum type of ('Yes', 'No').
Each row contains the course ID, course name, credits, major it belongs to, and whether the course is mandatory.
Table: enrollments
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| course_id | int |
| semester | varchar |
| grade | varchar |
| GPA | decimal |
+-------------+----------+
(student_id, course_id, semester) is the primary key (combination of columns with unique values) for this table.
Each row contains the student ID, course ID, semester, and grade received.
Write a solution to find the students who meet the following criteria:
Have taken all mandatory courses and at least two elective courses offered in their major.
Achieved a grade of A in all mandatory courses and at least B in elective courses.
Maintained an average GPA of at least 2.5 across all their courses (including those outside their major).
Return the result table ordered by student_id in ascending order.
Example:
Input:
students table:
+------------+------------------+------------------+
| student_id | name | major |
+------------+------------------+------------------+
| 1 | Alice | Computer Science |
| 2 | Bob | Computer Science |
| 3 | Charlie | Mathematics |
| 4 | David | Mathematics |
+------------+------------------+------------------+
Alice (student_id 1) is a Computer Science major and has taken both Algorithms and Data Structures, receiving an A in both. She has also taken Machine Learning and Operating Systems as electives, receiving an A and B respectively.
Bob (student_id 2) is a Computer Science major but did not receive an A in all required courses.
Charlie (student_id 3) is a Mathematics major and has taken both Calculus and Linear Algebra, receiving an A in both. He has also taken Probability and Statistics as electives, receiving an A and B respectively.
David (student_id 4) is a Mathematics major but did not receive an A in all required courses.
Note: Output table is ordered by student_id in ascending order.