Professional Documents
Culture Documents
DBI-Assigment MinhNV
DBI-Assigment MinhNV
ASSIGNMENT
REPORT
Class: SE1208
Page 2
10. Manager .................................................................................................................................. 28
IV. Explanation for Entity Relationships: ................................................................................ 29
1. Player – Club: ........................................................................................................................... 29
2. Manager – Club: ...................................................................................................................... 30
3. Player – Match Player - Match ............................................................................................... 31
4. Match Player – Foul – Card – Goal........................................................................................ 32
5. Stadium – Club - Match .......................................................................................................... 33
6. Match – Referee ....................................................................................................................... 34
D. Relational Mapping...................................................................................................................... 35
I. Step 1: Mapping Regular Entity ............................................................................................. 35
II. Step 2: Weak entities handling: .............................................................................................. 36
III. Step 3: Sub – entities handling: .......................................................................................... 36
IV. Step 4: 1 – N (1 to many) relationships handling: ............................................................. 36
V. Step 5: 1 – 1 relationship handling: ........................................................................................ 37
VI. Step 6: Many to many (M - N) relationships handling: ................................................... 38
VII. Muli – part and multi – value handling: ............................................................................ 38
E. Logical Design .............................................................................................................................. 39
I. Relational Schema .................................................................................................................... 39
II. Database Diagram .................................................................................................................... 40
III. Table Analysis ...................................................................................................................... 41
1. Stadium: .................................................................................................................................... 41
2. Player ........................................................................................................................................ 42
3. Referee ...................................................................................................................................... 43
4. Card ........................................................................................................................................... 44
5. Manager .................................................................................................................................... 44
6. Club ........................................................................................................................................... 45
7. Player_Club .............................................................................................................................. 46
8. Manager_Club.......................................................................................................................... 47
9. Match ........................................................................................................................................ 48
10. MatchPlayer ........................................................................................................................... 49
11. Foul .......................................................................................................................................... 50
12. Goal ......................................................................................................................................... 51
IV. Database statements used to create table ........................................................................... 52
1. Stadium table ............................................................................................................................ 52
2. Player table ............................................................................................................................... 52
Page 3
3. Referee table ............................................................................................................................. 52
4. Card table ................................................................................................................................. 53
5. Manager table........................................................................................................................... 53
6. Club table .................................................................................................................................. 53
7. Player_Club table..................................................................................................................... 53
8. Manager_Club table ................................................................................................................ 54
9. Match table ............................................................................................................................... 54
10. MatchPlayer table .................................................................................................................. 55
11. Foul table ................................................................................................................................ 55
12. Goal table ................................................................................................................................ 55
F. Queries, Store Procedures and Trigger ..................................................................................... 56
I. Sample Queries......................................................................................................................... 56
1. Query using ORDER BY ......................................................................................................... 56
2. Queries using INNER JOIN .................................................................................................... 57
3. Queries using aggregate functions:......................................................................................... 59
4. Queries using GROUP BY and HAVING clauses: ............................................................... 60
5. Queries that use sub – queries as relation .............................................................................. 61
6. Queries that use sub-query in the WHERE clause: .............................................................. 62
7. Queries that use partial matching in the WHERE clause: ................................................... 63
8. Queries that use self-join: ........................................................................................................ 64
Page 4
Table of Image
Figure 1: The Premier League Information..................................................................................... 8
Figure 2: Premier League Season information ............................................................................... 9
Figure 3: Premier League Fixtures ............................................................................................... 10
Figure 4: Premier League Results ................................................................................................. 11
Figure 5: Premier League 2017 – 2018 Tables ............................................................................. 12
Figure 6: Premier League Clubs ................................................................................................... 13
Figure 7: Premier League Players ................................................................................................ 14
Figure 8: Premier League Managers ............................................................................................ 15
Figure 9: Premier League Referees ............................................................................................... 16
Figure 10: Premier League Match Statistics ................................................................................. 17
Figure 11: Simplified ERD for Premier League 2017 – 2018 ....................................................... 19
Figure 12: Full ERD for Premier League 2017 – 2018................................................................. 20
Figure 13: Club entity .................................................................................................................... 21
Figure 14: Player entity ................................................................................................................. 22
Figure 15: Match player entity ...................................................................................................... 23
Figure 16: Foul entity .................................................................................................................... 24
Figure 17: Card entity ................................................................................................................... 24
Figure 18: Goal entity.................................................................................................................... 25
Figure 21: Stadium entity .............................................................................................................. 28
Figure 22: Manager entity ............................................................................................................. 28
Figure 23: Player – Club Relationship .......................................................................................... 29
Figure 24: Manager – Club Relationship ..................................................................................... 30
Figure 25: Player – MatchPlayer - Match Relationship .............................................................. 31
Figure 26: MatchPlayer – Foul – Card- Goal Relationship ........................................................ 32
Figure 27: Stadium – Club - Match Relationship ......................................................................... 33
Figure 28: Match - Referee Relationship...................................................................................... 34
Figure 29: Logical Design ............................................................................................................ 40
Figure 30: Result of query using order by .................................................................................... 56
Figure 31: Result of query using INNER JOIN ............................................................................ 57
Figure 32: Result of query using INNER JOIN ............................................................................ 58
Figure 33: Result of query using aggregate function ................................................................... 59
Figure 34: Result of query using GROUP BY and HAVING clause ............................................. 60
Page 5
Figure 35: Result of query using sub query as relation ................................................................ 61
Figure 36: Result of query using sub query in where clause ........................................................ 62
Figure 37: Result of query using sub query in where clause ........................................................ 62
Figure 38: Result of query using partial matching in WHERE clause ......................................... 63
Figure 39: Result of query using self - join................................................................................... 64
Figure 40: Store procedure........................................................................................................... 65
Figure 41: Trigger ........................................................................................................................ 66
Page 6
A. Background
I. General
1. Design and develop a database system for a sport tournament season.
2. The database must consist of at least six tables populated with data.
3. The database is to support queries that would typically be submitted to the system
for the topical chosen area.
4. Using Chen’s Notation for Entity Relationship Diagram (ERD).
5. Map the EER model into a relational data model normalized at least 3rd normal Form.
6. Using appropriate SQL commands create a set of database tables in MS SQL Server
2008+. You should also show all constraints used in the creation of the tables.
II. Specification:
1. Your database must contain one view, one trigger, on store procedure and an index
(describe why).
2. Create 10 sample queries that demonstrate the expressiveness of your database
system. Your queries must demonstrate different aspects of the system.
III. Destination
Design and develop a database system for English Premier League 2017 – 2018.
IV. Tools
1. Microsoft SQL Database Management Studio 2016
2. Microsoft Visio 2016 Professional
3. Microsoft Word 2016 Professional
4. https://www.generatedata.com
Page 7
B. Preview
I. Introduce The Premier League
The Premier League is an English professional league for men's association football
clubs. At the top of the English football league system, it is the country's primary football
competition. Contested by 20 clubs, it operates on a system of promotion and relegation with
the English Football League. Welsh clubs that compete in the English football league system
can also qualify. Welsh clubs that compete in the English football league system can also
qualify.
The Premier League is a
corporation in which the 20 member
clubs act as shareholders. Seasons run
from August to May. Teams play 38
matches each (playing each team in
the league twice, home and away),
totaling 380 matches in the season.
Most games are played on Saturday
and Sunday afternoons; others during
weekday evenings. It is colloquially
known as the Premiership and outside
the UK it is commonly referred to as
the English Premier League (EPL).
In total, 49 clubs have
competed since the inception of the
Premier League in 1992. Six of them
have won the title: Manchester United
(13), Chelsea (5), Arsenal (3),
Manchester City (2), Blackburn
Rovers (1) and Leicester City (1).
Figure 1: The Premier League Information
Page 8
II. Information for a Premier League Season
A Premier League season contains a lot of information that must be stored. Below is
the most necessary
information:
Fixtures
Results
Tables
Clubs
Players
Managers
Referees
Match statistics
In fact, a Premier League season has much more information than above one such as broadcast rights,
transfers, tickets, safeguarding or lots of other. However, to simplify the work of designing and
developing databases system as well as the structure of database, I will only concentrate on the main
information that I listed above.
(Source: https://www.premierleague.com/home)
Page 9
1. Fixtures
In order to control the matches time for broadcast, transfers purpose or fitting with all
other events like Christmas, New Years, World Cup Qualifiers, etc., before the first game,
the fixtures are made for a whole season – usually from August to May.
The fixtures contain lots of records. Each record includes information of a match that
has been scheduled: home team, guest team, date and time that the match will be played,
the stadium where the match will be hold.
(Source: https://www.premierleague.com/fixtures)
Page 10
2. Results:
Results is one of the most information of a football match. The results are the status
win, lose or draw, the score of home and away team. The winner will receive 3 points, the
looser will get no point and if the result is draw, both two team get 1 point.
(Source: https://www.premierleague.com/results)
Page 11
3. Tables
After a match, each teach will get their corresponding point (3 points if win, 1 point if
draw and 0 point if lose). This point will be statistics to create tables. The tables will be
updated after a match and will show ranking of each team in the league. The tables usually
contain club name with their position, how many game that played, games they won,
drawn and lost, number of goals for, goal again, goal different, their point and their
recently form.
(Source: https://www.premierleague.com/tables)
Page 12
4. Clubs
In the Premier League history, there are many different clubs that had competed at this
league, but in this assignment, I will only concern about the most recently season, the
Premier League 2017 – 2018. So, there are only have 20 clubs compete at this league this
season. A club information includes their name, their address, their stadium, their CEO,
etc.
(Source: https://www.premierleague.com/clubs)
Page 13
5. Players
The Premier League has many players that come from many different nations in the
world. The player will play for a club for a certain time according to the contract between
the club and player. One player can only play for one club at one time but he can play for
more than one club at the season if he moves to another club at the transfer time. The
player information includes their name, date of birth, weight, height, position, nationality,
etc.
(Source: https://www.premierleague.com/players)
Page 14
6. Manager
Like player, managers come from many different country and will manage a club in a
certain time corresponding to the contract between the manager and the club. A manager
could also manage different team in a season but only one club at one time. A manager
information includes their name, nationality and the club they manage.
(Source: https://www.premierleague.com/managers)
Page 15
7. Referees
Referees are the ones who take charge of a match and ensure that the match is played
according to the laws of sport. Usually there are four referees in a match, one main
referee, two assistant referees and one fourth referee. In this assignment, I will only care
about the main referee and will ignore all other referees. Main referee is the one who has
highest authority to decide a situation in a match. A referee information contains name,
nationality, number of experienced years and will take charge of which match.
(Source: https://www.premierleague.com/referees/appointments)
Page 16
8. Match statistics
Match statistics are considered as a match report that holding information about the
match such as the final score, the player that score goals, the referees who take charge of a
match a so on. Typically, match statistics divide into 2 categories: player statistics and team
statistics. Players statistics is about number of shots, shot on target, goal, run distances,
number of fouls commit, receive, number of card receive, etc. Team statistics usually
contain the possession, pass success, corners, aerials won, etc.
(Source: https://www.whoscored.com/Matches/1190228/Live/England-Premier-
League-2017-2018-Manchester-City-Burnley)
Page 17
C – Entity Relationship Diagram (Using Chen ‘s Notation)
I. Business Rules and Assumption Rules
1. Business Rules
1. There are 20 clubs play at Premier League each season
2. Each team must have player to play at Premier League
3. One team can have 25 players in maximum.
4. Player must belong to a club.
5. Player can only play for one club at one time but during the season, they can play for more
than one club if they move to another club at the transfer time.
6. One club must have one manager
7. A manager can only manage one club at one time but they can move to other club at
transfer time.
8. A squad for a match contains 16 players in maximum (11 for line-up and 5 sub players)
9. In a match, a club can sub 3 players in maximum
10. Each club owns a stadium and a stadium belongs to a club
11. A match is between 2 club, a host club and a guest club.
12. A match always plays at stadium of host club
13. A match is taken charge by a referees
14. A player could receive 2 yellow cards in maximum.
15. 2 Yellow cards equivalent 1 red card. Player received 2 yellow cards or 1 red card in a
match will be kicked out of that match.
16. A goal can score by any time in match. The time always between 1 and 90.
2. Assumption Rules
1. A player, Manager, Referee using a positive integer for identifier instead of their SSN.
2. One team manage by only one manager, the main one.
3. One match is taken charge by one referee, the main one.
4. The type of player is only one of these values: Goal keeper, Defender, Midfielder,
Forward
Page 18
II. Entity Relationship Diagram (ERD) for Database
1. Simplified Entity Relationship Diagram
Stadium
Owned
1
Card
Player N Play for N Club N Manage N Manager
1
Receive
1 1 1
Host Guest
N be
Foul N 1 1
Commit 1 N
1 1 Score
Assist
N Goal
N
Page 19
2. Full Entity Relationship Diagram for Database
Height
1 be Sub 1 Nationality
ShirtNo Time
1 1
1
1
Owned
in
N Capacity
1
1
Foul N Match N take charge of
Date
Type 1 RefereeID
N
ID GuestScore
1 Score N Nationality
GoalID
Card
Type
Offset
Type
Page 20
III. Explanations for entities:
1. Club:
ClubName
ClubID
Number of
Club players
- Definition: A club is a group of people formed for the purpose of playing football. In the
English Premier League 2017 – 2018, there are 20 clubs compete. The maximum players
that each club can have are 25 (maximum 17 foreign players (this rule are ignored in this
report)). A club at Premier League is usually owned by a CEO or an organization.
However, in this report, I will ignore that information.
- Attributes of Club: Club ID, Club Name, and may be number of players in the club.
- Club ID usually is a 3-character of club name. Club ID is unique and using to identify a
club.
This is primary key for the Club entity.
- Number of players is derived attribute because it can be count easily.
Page 21
2. Player
PlayerName
DOB
PlayerID
Nationality
Player Position
Height
ShirtNo
- Definition: Player is the one who directly play a match in the Premier League. To play at
this league, player must have a legal contract with one of 20 clubs play at Premier League
of that season, for this report is 2017 – 2018 season.
- Attributes of Player: Player ID, Name, DOB, Nationality, Height, Position and Shirt
Number.
- One player has his ID to differ from other players. In fact, a player has his unique SSN to
identity them but to simply find the process of collecting data, I will use Player ID instead.
Player ID is just a positive integer and one player has one ID.
PlayerID is primary key for player entity.
- A player can come from many different countries but a club can’t have more than 17 non-
English players.
Page 22
3. Match Player:
Pass success
Tackles
MatchPlayer
Shots
Running Distances
ID
- Definition: A club could include 25 players in maximum but in a match, a club could only
register 16 players (11 players for lineup and 5 sub players). However, in a match, a player
could only sub 3 players in total.
- Attributes: A match player include some information: number of shots, the percentage of
pass success, number of dribbles, number of aerials won, number of tackles, running
distances. I also add a ID attributes to identify each record.
ID is primary key for Match Player entity.
- In fact, a match player can divide into many types: goal keeper, defender, midfielder,
forward with different attributes for each type. But in this assignment, I will not divide
Match Player into that types.
Page 23
4. Fouls
Foul
Type
ID
- Definition: In a match, there are many different foul such as kicking, tripping, charge into,
pushing an opponent, offside, touch the ball with hands.
- Attributes: ID, type of fouls
ID is primary key for this entity.
5. Card
Card
Color ID
- Definition: In a match, player can receive card from referee for commit foul or other not
bad behavior. There are two type of card: yellow card and red card. Two yellow cards
equivalent to a red card. If player receive a red card, they can’t continue to play match.
- Attributes: ID, color of card
ID is primary key for this entity.
Page 24
6. Goal:
Goal Minute
GoalID Offset
Type
- Definition: Goal is the most important part of a match. A goal could be made by many
different part of player’s body such as left foot, right foot, head, chest.
- Attributes: Goal ID, type of goal, minute, offset.
GoalID is primary key for Goal entity.
- There are many different types of goal but I this assignment, I assume that there only three
types of goal: directly goal (a goal make by player of …), penalty goal, own goal.
- Offset attribute show the extra minutes when the goal is scored. By default, the offset is 0.
Page 25
7. Match:
Match
Date GuestScore
Status HostScore
- Definition: In Premier League and all other football league in the world, a match includes
clubs (1 home clubs and 1 away club). The result of the match is calculated by the host
score and the guest score. If the host score equal to the guest score, the match is drawn.
Otherwise, the club score more is the winner.
- Attributes: Date of the match, status of the match (scheduled, postponed, playing,
finished), the host and guess score
- This is a week entity that can have its attribute to make a primary key. Match use 2 foreign
key from club table (the home club ID and the away club ID) with the attribute Date to
form a primary key.
Primary key is combine of hostID, awayID and date.
Page 26
8. Referee
Referee
Nationality
RefereeID
Name
- Definition: Usually there are four referees in a match, one main referee, two assistant
referees and one fourth referee. However, in this assignment, I will only care about the
main referee and will ignore all other referees. Main referee is the one who has highest
authority to decide a situation in a match. A referee information contains name,
nationality, number of experienced years and will take charge of which match.
- Attributes: Referee ID, Name, Nationality.
- Like player entity, referee has their own SSN to identity but to simplify the work of
collecting data, I just use a positive integer for each record in the referee entity.
Referee ID is the primary key.
Page 27
9. Stadium:
Stadium Capacity
StadiumID
Address
Name
- Definition: Each club plays in the Premier League has their own stadium. This stadium
holds the match between the club own it as a home team and another team as an away
team.
- Attributes: Stadium ID, Name, Address and Capacity
- Stadium ID is just a positive integer using to identity each record in the table
StadiumID is primary key.
10. Manager
Manager
Name
ManagerID
Nationality
- Definition: Each club is coached by a manager. Actually, a club could have many
manager (1 main coach and many other assistant coaches). But in this assignment, I
assume that one club has only one coach, the main one.
- Attributes: Manager ID, Name and Nationality.
- Manager ID is a positive integer and it’s unique
ManagerID is primary key for Manager entity.
Page 28
IV. Explanation for Entity Relationships:
1. Player – Club:
EndDate
StartDate
Salary
Club
- One player only plays for one club at one time, but in a season he can play for many
club if he moves from one club to another one at the transfer time. One club can have many
players (maximum 25 player). If a player wants to play for a club or the club want one player
plays for their team, they must sign a contract. A contract contains information of player and
clubs that they play for. It also contains the start date and end date of a contract, the salary that
player will have during the time he plays for the club.
- There is no club that have no players play at Premier League and there a no player
who does not play for any club at Premier League stored.
Page 29
2. Manager – Club:
EndDate StartDate
Club N Manage
Manager
- Like player, manager only coaches one club at one time but during the Premier
League season, they can coach many different clubs if they move to another club the at the
transfer time. During the season, one club could have different manager so one club have
many manager and one manager can coach many clubs too. If manager want coach a club
or a club want a manager coach their team, they must sign a contract. A contract contains
information of both side, the start date and end date of the contract.
- In the Premier League, there is no club have no manager and there are no manager
that not coach any team stored.
Page 30
3. Player – Match Player - Match
Time
1 Sub
Player 1 be N MatchPlayer 1
in
Match
- A club contains 25 players in maximum but not all of them can play in a match. In the
Premier League, a squad for a match contains 16 players in maximum (11 players for lineup
and 5 sub players). A Match player must be a player but a player might not be a match player.
In a match, a club can sub maximum 3 players but it not requires. A club could not change any
players or not use all of 3 times change player.
- A match player must play for a match and a match must contain match player. No
match plays if not have player and there is no match player that not play for match.
Page 31
4. Match Player – Foul – Card – Goal
1 MatchPlayer 1 Score
1
Commit 1 Assist
Receive N
Foul N Goal
Receive
1 Card
- In a match, a match player can commit a foul and also receive a foul. A committed
foul can be different in type and could commit on some other player or not. So a foul could be
receive by a player or not. If a player commits a fouls, depend on the rules, the player may
receive a card (yellow card or red card).
- In a match, match player a scores one or many goal but can also scores no goal. Each
goal can by assist by some else player or not. No goal exist that not scored by players.
Page 32
5. Stadium – Club - Match
1 Guest
Club
1
Host
1
Owned
1
1
Stadium Match
- Every club in the Premier League 2017 – 2018 owned a stadium and every stadium
that stored is owned by a club. There is no club that don’t have any stadium and there is no
stadium that stored isn’t owned by any club.
- All matches in the Premier League 2017 – 2018 include 2 team (a host team and a
guest team). Host team will host the match at their own stadium. No match plays that don’t
have host and guest team.
Page 33
6. Match – Referee
Referee
- A match in the Premier League 2017 – 2018 is taken charge by 4 referees (a main
referee, 2 assistant referees that help out with decisions such as thrown-ins and offside, the
fourth referee assists with substitutions and keep a check on the managers). However, in this
assignment, I assume that there a only one referee take charge of a match and that is the main
one.
- Every match is taken charge by a referee and a referee must take charge at least one
match. There is no match that not taken charge by any referee and there is no referee that take
charge no match. During the Premier League season, a referee can take charge many match.
Page 34
D. Relational Mapping
I. Step 1: Mapping Regular Entity
- For each regular (not weak) entity E, create a relation R including all necessary attributes
of E, one column for each attribute.
- Choose the key of entity E as the primary key of R.
- If the key of E includes more than one attributes, the set of corresponding columns in R
will form its primary key
- MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running distances)
key.
Page 35
II. Step 2: Weak entities handling:
- Find all the weak entities in the ERD, for each weak entity E create a relation R and the
primary key of R includes the attribute of it and a foreign key from another relation.
- Match (Date, Status, HostID, GuestID) has primary key is combine of (Date, HostID,
- On the many – relationship relation of the relationship, add its foreign keys refers to the
MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running
distances, PlayerID)
Add foreign key (HostID, GuestID, Date) from Match to Match Player
MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running
Page 36
Match Player(1) – Commit / Receive – Foul (N):
Add foreign key CommitBy, ReceiveBy reference to ID from Match Player to Foul
Add foreign key ScoreBy, AssistBy reference to ID from Match Player to Goal
- Choose a key from one entity and add it to other entity as foreign key.
- 1 – 1 relationship:
Page 37
VI. Step 6: Many to many (M - N) relationships handling:
- Steps:
New table contains two foreign keys – one from each of the participants in the
relationship
The primary key of the new table is the combination of the two foreign keys:
- M – N relationships:
Create a new table named Player_Club with attributes from relationship attributes.
Add PlayerID reference to PlayerID from Player, ClubID reference to ClubID from
Club to Player_Club
Player_Club (PlayerID, ClubID, StartDate, EndDate, Salary) has primary key is the
Create a new table named Manager_Club with attributes from relationship attributes.
Manager_Club(StartDate, EndDate)
Page 38
E. Logical Design
I. Relational Schema
List of relations in the database logical design:
- MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running distances,
Page 39
II. Database Diagram
Page 40
III. Table Analysis
1. Stadium:
Name NVARCHAR(50) No
Address NVARCHAR(150) No
Capacity INT No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each stadium has a StadiumID using for identifier so StadiumID is primary key
of Stadium.
Page 41
2. Player
Nationality NVARCHAR(50) No
DOB DATE No
Height INT No
Position NVARCHAR(10) No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each player has a PlayerID using for identifier so PlayerID is primary key of
Player.
Position is of a player in one of the values in the set {'Goalkeeper',
'Defender', 'Midfielder', 'Forward'}. So the constraint
CHECK is added to check whether if the data is valid (in the set) or not.
Page 42
3. Referee
Name NVARCHAR(50) No
Nationality NVARCHAR(50) No
YearOfExp INT No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each referee has a RefereeID using for identifier so RefereeID is primary key of
Referee
The YearOfExp attribute in Referee table show the number of experience year of
a referee and of course, it must be a positive integer. So the constraint CHECK is
added to check if YearOfExp is greater or equal to zero or not.
Page 43
4. Card
Color NVARCHAR(6) No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each card has a CardID using for identifier so CardID is primary key of Card
Color must be only Yellow or Red so I added a constraint CHECK to check if the
data is valid
CONSTRAINT Card_CHK CHECK (Color IN ('Red',
'Yellow'))
5. Manager
Name NVARCHAR(50) No
Nationality NVARCHAR(50) No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each manager has a ManagerID using for identifier so ManagerID is primary
key of Manager
Page 44
6. Club
ClubName NVARCHAR(50) No
StadiumID INT No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
Each club has a ClubID using for identifier so ClubID is primary key of Club
The data in column StadiumID of table Club must be consistent with the data of
StadiumID of table Stadium. So there is a foreign key Club_FK_Stadium
between to table.
Page 45
7. Player_Club
StartDate DATE No
EndDate DATE No
Salary Float No
ShirtNo INT No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
The contract between the club and the player, so the PlayerID from Player and
ClubID from Club is unique for each contract. The two columns (PlayerID,
ClubID) are set to be the primary key of the table
CONSTRAINT Player_Club_PK PRIMARY KEY (PlayerID,
ClubID)
The data in two columns (PlayerID, ClubID) must be consistent with the data
from the original table. So there are foreign keys between those table
Page 46
8. Manager_Club
StartDate DATE No
EndDate DATE No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
The contract between the club and the player, so the ManagerID from Manager
and ClubID from Club is unique for each contract. The two columns (Manager,
ClubID) are set to be the primary key of the table
The data in two columns (ManagerID, ClubID) must be consistent with the data
from the original table. So there are foreign keys between those table
CONSTRAINT Manager_Club_FK_Manager FOREIGN KEY
(ManagerID) REFERENCES Manager(ManagerID)
CONSTRAINT Manager_Club_FK_Club FOREIGN KEY
(ClubID) REFERENCES Club(ClubID)
The the EndDate must greater than StartDate so I added a CHECK constraint to
check it
CONSTRAINT Manager_Club_CHK CHECK (EndDate >
StartDate)
Page 47
9. Match
Status NVARCHAR(10) No
RefereeID INT No
Constraints Descriptions:
All columns in this table must be filled so each column has NOT NULL
constraint.
The combination of (HostID, GuestID, Date) make each record unique so it is
primary key of this table
CONSTRAINT Match_PK PRIMARY KEY (HostID, GuestID,
Date)
The data in columns (HostID, GuestID, RefereeID) must be consistent with the
data from the original table. So there are foreign keys between those table
The status of a match can only one of the values: Scheduled, Playing, Finished,
Postponed. So I added a CHECK constraint
Page 48
10. MatchPlayer
isMain BIT No
PlayerID INT No
HostID INT No
GuestID INT No
Date DATE No
Constraints Descriptions:
All columns (except SubBy and SubTime) in this table must be filled so they
have NOT NULL constraint.
Each MatchPlayer has a ID using for identifier so ID is primary key of
MatchPlayer
The data in columns (PlayerID, HostID, GuestID, Date) must be consistent with
the data from the original table. So there are foreign keys between those table
CONSTRAINT MatchPlayer_FK_Player FOREIGN KEY
(PlayerID) REFERENCES Player(PlayerID)
CONSTRAINT MatchPlayer_FK_Match FOREIGN KEY
(HostID, GuestID, Date) REFERENCES Match(HostID,
GuestID, Date)
The ID of sub player must be the ID of registered player, so it must be the ID of
Match Player
Page 49
11. Foul
Type NVARCHAR(100) No
CommitBy INT No
Constraints Descriptions:
All columns (except ReceiveBy and CardID) in this table must be filled so they
have NOT NULL constraint.
Each Foul has a ID using for identifier so ID is primary key of Foul.
The data in columns (CommitBy, ReceiveBy, CardID) must be consistent with
the data from the original table. So there are foreign keys between those table
CONSTRAINT Foul_FK_CommitPlayer FOREIGN KEY
(CommitBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Foul_FK_ReceivePlayer FOREIGN KEY
(ReceiveBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Foul_FK_Card FOREIGN KEY (CardID)
REFERENCES Card(ID)
Page 50
12. Goal
Minute NVARCHAR(100) No
Offset INT No
Type NVARCHAR(10) No
ScoreBy INT No
Constraints Descriptions:
All columns (except AssistBy) in this table must be filled so they have NOT
NULL constraint.
Each Goal has a ID using for identifier so ID is primary key of Goal.
The data in columns (ScoreBy, AssitBy) must be consistent with the data from the
original table. So there are foreign keys between those table
Page 51
IV. Database statements used to create table
---CREATE DATABSE---
CREATE DATABASE PREMIER_LEAGUE
USE PREMIER_LEAGUE
1. Stadium table
2. Player table
3. Referee table
Page 52
4. Card table
5. Manager table
6. Club table
7. Player_Club table
Page 53
8. Manager_Club table
9. Match table
Page 54
10. MatchPlayer table
CREATE TABLE MatchPlayer (
ID INT PRIMARY KEY,
isMain BIT NOT NULL,
PlayerID INT NOT NULL,
HostID INT NOT NULL,
GuestID INT NOT NULL,
Date DATE NOT NULL,
SubBy INT,
SubTime INT,
CONSTRAINT MatchPlayer_FK_Player FOREIGN KEY
(PlayerID) REFERENCES Player(PlayerID),
CONSTRAINT MatchPlayer_FK_Match FOREIGN KEY
(HostID, GuestID, Date) REFERENCES Match(HostID,
GuestID, Date),
CONSTRAINT MatchPlayer_FK_MatchPlayer FOREIGN
KEY (SubBy) REFERENCES MatchPlayer(ID)
)
11. Foul table
CREATE TABLE Foul (
ID INT PRIMARY KEY,
Type NVARCHAR(100) NOT NULL,
CommitBy INT NOT NULL,
ReceiveBy INT,
CardID INT
CONSTRAINT Foul_FK_CommitPlayer FOREIGN KEY
(CommitBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Foul_FK_ReceivePlayer FOREIGN KEY
(ReceiveBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Foul_FK_Card FOREIGN KEY (CardID)
REFERENCES Card(ID)
)
12. Goal table
CREATE TABLE Goal (
GoalID INT PRIMARY KEY,
Minute INT NOT NULL,
Offset INT,
Type NVARCHAR(10) NOT NULL,
ScoreBy INT NOT NULL,
AssistBy INT
CONSTRAINT Goal_FK_ScorePlayer FOREIGN KEY
(ScoreBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Goal_FK_AssistPlayer FOREIGN KEY
(AssistBy) REFERENCES MatchPlayer(ID),
CONSTRAINT Goal_CHK CHECK (Minute >=1 and Minute
<= 90 and Type IN ('Direct', 'Own goal', 'Penalty'))
)
Page 55
F. Queries, Store Procedures and Trigger
I. Sample Queries
1. Query using ORDER BY
- Question: Display referees information that sort by their number of experence years
descending
- Query:
- Result:
Page 56
2. Queries using INNER JOIN
- Question: Display Player Name, Club Name that they play for and their salary. Sort the
result by salary descending
- Query:
- Result:
Page 57
- Question: Display Manager Name, Club Name that they manage, Start Date and End Date
of the contract between the Manager and the Club
- Query:
- Result:
Page 58
3. Queries using aggregate functions:
- Question: Display players that have their age over 30 years old. The information of player
includes their name, their nationality and their age.
- Query:
- Result:
Page 59
4. Queries using GROUP BY and HAVING clauses:
- Question: Display number of players born between 1985 and 1995 for each year. The first
column is the year and the second column is number of players was born in this year
- Query:
- Result:
Page 60
5. Queries that use sub – queries as relation
- Question: Display information about the player that have scored a goal. The information
includes Player Name, Club Name that player plays for and Number of goals that players
have scored.
- Query:
- Result:
Page 61
6. Queries that use sub-query in the WHERE clause:
- Question: Display all information of a player that have ever committed a foul
- Query:
- Question: Display = information of a stadium that have hold a match in this season. The
information includes name of stadium, club that owns that stadium and the capacity of it.
- Query:
Page 62
7. Queries that use partial matching in the WHERE clause:
- Question: Display player information of all player that their name contains “in”
- Query:
- Result:
Page 63
8. Queries that use self-join:
- Question: Display all substitution event in this season. Each record includes name of
player who out, in and minute that make the substitution.
- Query:
- Result:
Page 64
II. Stored Procedures
Get result of finished matches
- Create procedure:
CREATE PROCEDURE SP_GET_RESULT
AS
BEGIN
SELECT c1.ClubName as 'Host Name', host.[Host score],
guest.[Guest Score], c2.ClubName as 'Guest Name' FROM (
Club c1 INNER JOIN
(SELECT m.HostID, m.Date, m.GuestID, SUM (CASE WHEN
g.ScoreBy IS NULL THEN 0 ELSE 1 END) as 'Host score' FROM
Goal g
INNER JOIN MatchPlayer mp ON mp.ID = g.ScoreBy
INNER JOIN Player p ON p.PlayerID = mp.PlayerID
INNER JOIN Player_Club p_c ON p_c.PlayerID =
p.PlayerID
INNER JOIN Match m ON m.HostID = p_c.ClubID
WHERE m.Status = 'Finished'
GROUP BY m.HostID, m.GuestID, m.Date) host
ON host.HostID = c1.ClubID
INNER JOIN
(SELECT m.HostID, m.Date, m.GuestID, SUM (CASE WHEN
g.ScoreBy IS NULL THEN 0 ELSE 1 END) as 'Guest Score' FROM
Goal g
INNER JOIN MatchPlayer mp ON mp.ID = g.ScoreBy
INNER JOIN Player p ON p.PlayerID = mp.PlayerID
INNER JOIN Player_Club p_c ON p_c.PlayerID =
p.PlayerID
RIGHT JOIN Match m ON m.GuestID = p_c.ClubID
WHERE m.Status = 'Finished'
GROUP BY m.HostID, m.GuestID, m.Date) as guest
ON guest.Date = host.Date and guest.GuestID =
host.GuestID and guest.HostID = host.HostID
INNER JOIN club c2 ON c2.ClubID = guest.GuestID
)
END
- Execute procedure:
EXEC SP_GET_RESULT
- Result:
Page 65
III. Trigger:
Not allow to sub more than 3 players:
- Create trigger:
CREATE TRIGGER NOT_ALLOW_SUB_MORE_THAN_3_Players
ON MatchPlayer
FOR INSERT, UPDATE
AS
BEGIN
DECLARE @Date DATE;
DECLARE @HostID INT;
DECLARE @GuestID INT;
DECLARE @COUNT INT;
IF @COUNT > 3
BEGIN
RAISERROR('You can not sub more than 3
players', 1, 1);
ROLLBACK TRANSACTION
END
END
- Test trigger:
UPDATE MatchPlayer SET SubBy = 51
WHERE ID = 48
Run successfully
UPDATE MatchPlayer SET SubBy = 51, SubTime = 82
WHERE ID = 46
Page 66