SQL Exercise: Matches, goalless draws in group stage matches
13. From the following table, write a SQL query to count the number of matches that ended in a goalless draw at the group stage. Return number of matches.
Sample table: match_details
match_no | play_stage | team_id | win_lose | decided_by | goal_score | penalty_score | ass_ref | player_gk
----------+------------+---------+----------+------------+------------+---------------+---------+-----------
1 | G | 1207 | W | N | 2 | | 80016 | 160140
1 | G | 1216 | L | N | 1 | | 80020 | 160348
2 | G | 1201 | L | N | 0 | | 80003 | 160001
2 | G | 1221 | W | N | 1 | | 80023 | 160463
3 | G | 1224 | W | N | 2 | | 80031 | 160532
3 | G | 1218 | L | N | 1 | | 80025 | 160392
4 | G | 1206 | D | N | 1 | | 80008 | 160117
4 | G | 1217 | D | N | 1 | | 80019 | 160369
5 | G | 1222 | L | N | 0 | | 80011 | 160486
..........
51 | F | 1207 | L | N | 0 | | 80007 | 160140
Sample Solution:
-- This SQL query calculates the count of distinct 'match_no' values in the 'match_details' table
-- where certain conditions are met: 'win_lose' is 'D', 'goal_score' is 0, and 'play_stage' is 'G'.
SELECT COUNT(DISTINCT(match_no))
-- COUNT(DISTINCT(match_no)) counts the number of unique 'match_no' values in the result set.
FROM match_details
-- 'match_details' is the name of the table being queried.
WHERE win_lose='D'
-- The WHERE clause filters rows where the 'win_lose' column has the value 'D'.
AND goal_score=0
-- Further filters rows where the 'goal_score' column has the value 0.
AND play_stage='G';
-- Further filters rows where the 'play_stage' column has the value 'G'.
Sample Output:
count
-------
4
(1 row)
Code Explanation:
The said query in SQL that selects the count of distinct match numbers where the win/lose column has a value of 'D', the goal_score column has a value of 0, and the play_stage column has a value of 'G' from the table named 'match_details'.
The WHERE clause filters the rows where the value of the win_lose column is equal to 'D', the value of the goal_score column is equal to 0, and the value of the play_stage column is equal to 'G'.
Therefore, the query would return a single value, which is the count of unique match_no values.
Relational Algebra Expression:
Relational Algebra Tree:
Go to:
PREV : Matches, first half with no stoppage time added.
NEXT : Matches, one goal wins except decided by penalty kicks.
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.
