SQL Exercise: Within each half of play, find the number of bookings
27. From the following table, write a SQL query to count the number of bookings in each half of play within the normal play schedule. Return play_half, play_schedule, number of booking happened.
Sample table: player_booked
match_no | team_id | player_id | booking_time | sent_off | play_schedule | play_half
----------+---------+-----------+--------------+----------+---------------+-----------
1 | 1216 | 160349 | 32 | | NT | 1
1 | 1216 | 160355 | 45 | | NT | 1
1 | 1207 | 160159 | 69 | Y | NT | 2
1 | 1216 | 160360 | 78 | | NT | 2
2 | 1221 | 160470 | 14 | | NT | 1
2 | 1201 | 160013 | 23 | | NT | 1
2 | 1201 | 160013 | 36 | | NT | 1
2 | 1201 | 160014 | 63 | | NT | 2
2 | 1221 | 160472 | 66 | | NT | 2
.......
51 | 1214 | 160302 | 122 | | ET | 2
Sample Solution:
SQL Code:
-- This SQL query calculates the count of bookings for each play half and play schedule in the 'player_booked' table.
SELECT play_half, play_schedule, COUNT(*)
-- Selects the 'play_half', 'play_schedule', and the count of rows for each group.
FROM player_booked
-- 'player_booked' is the name of the table being queried.
WHERE play_schedule='NT'
-- The WHERE clause filters rows where the 'play_schedule' column has the value 'NT'.
GROUP BY play_half, play_schedule;
-- Groups the results by 'play_half' and 'play_schedule'.
Sample Output:
play_half | play_schedule | count
-----------+---------------+-------
1 | NT | 61
2 | NT | 123
(2 rows)
Code Explanation:
The said query in SQL will retrieve "play_half", "play_schedule", and number of players booked in normal time schedule from the 'player_booked' table.
The WHERE clause filter the rows where the value of "play_schedule" is equal to 'NT'
A GROUP BY groups the results by play_half, play_schedule columns.
Relational Algebra Expression:
Relational Algebra Tree:
Go to:
PREV : Find the number of penalty shots taken by the teams.
NEXT : Find the number of booking happened in stoppage time.
Practice Online
Sample Database: soccer
Query Visualization:
Duration:
Rows:
Cost:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
