Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

DBI

ASSIGNMENT
REPORT

Student: Nguyen Vu Minh

Student’s Roll Number: SE05309

Class: SE1208

Subject: Introduction to Databases (DBI202)

Instructor: Ngo Tung Son


Table of Contents
A. Background .................................................................................................................................... 7
I. General ........................................................................................................................................ 7
II. Specification: .............................................................................................................................. 7
III. Destination .............................................................................................................................. 7
IV. Tools ........................................................................................................................................ 7
B. Preview ............................................................................................................................................ 8
I. Introduce The Premier League ................................................................................................. 8
II. Information for a Premier League Season............................................................................... 9
1. Fixtures ..................................................................................................................................... 10
2. Results: ...................................................................................................................................... 11
3. Tables ........................................................................................................................................ 12
4. Clubs.......................................................................................................................................... 13
5. Players ....................................................................................................................................... 14
6. Manager .................................................................................................................................... 15
7. Referees ..................................................................................................................................... 16
8. Match statistics ......................................................................................................................... 17
C – Entity Relationship Diagram (Using Chen ‘s Notation) ............................................................ 18
I. Business Rules and Assumption Rules ................................................................................... 18
1. Business Rules .......................................................................................................................... 18
2. Assumption Rules..................................................................................................................... 18
II. Entity Relationship Diagram (ERD) for Database ............................................................... 19
1. Simplified Entity Relationship Diagram ................................................................................ 19
2. Full Entity Relationship Diagram for Database .................................................................... 20
III. Explanations for entities:..................................................................................................... 21
1. Club: .......................................................................................................................................... 21
2. Player ........................................................................................................................................ 22
3. Match Player: ........................................................................................................................... 23
4. Fouls .......................................................................................................................................... 24
5. Card ........................................................................................................................................... 24
6. Goal: .......................................................................................................................................... 25
7. Match: ....................................................................................................................................... 26
8. Referee ...................................................................................................................................... 27
9. Stadium: .................................................................................................................................... 28

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

(Source: Wikipedia (https://en.wikipedia.org/wiki/Premier_League))

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

Figure 2: Premier League Season information

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.

Figure 3: Premier League Fixtures

(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.

Figure 4: Premier League Results

(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.

Figure 5: Premier League 2017 – 2018 Tables

(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.

Figure 6: Premier League Clubs

(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.

Figure 7: Premier League Players

(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.

Figure 8: Premier League Managers

(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.

Figure 9: Premier League Referees

(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.

Figure 10: Premier League Match Statistics

(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

N Match N take charge of 1 Referee


MatchPlayer N in
1
Receive 1 1
Sub
1 Time

1 1 Score

Assist
N Goal
N

Figure 11: Simplified ERD for Premier League 2017 – 2018

Page 19
2. Full Entity Relationship Diagram for Database

PlayerName DOB ClubName


PlayerID EndDate ManagerID
ClubID Number of EndDate StartDate
Position StartDate players
Salary
Nationality
Player N Play for N Club N Manage N Manager Name

Height

1 be Sub 1 Nationality
ShirtNo Time
1 1
1
1
Owned

N MatchPlayer Host Guest StadiumID


1
1
Name
1 Stadium
N
Commit Receive
1 1 Address

in
N Capacity
1
1
Foul N Match N take charge of

Date
Type 1 RefereeID
N
ID GuestScore

Receive Status HostScore 1 Name


Referee

1 Score N Nationality
GoalID
Card

Type

Color ID Assist N Goal Minute

Offset

Type

Figure 12: Full ERD for Premier League 2017 – 2018

Page 20
III. Explanations for entities:
1. Club:

ClubName

ClubID
Number of
Club players

Figure 13: Club entity

- 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

Figure 14: Player entity

- 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:

Dribbles Aerials Won

Pass success
Tackles
MatchPlayer

Shots

Running Distances
ID

Figure 15: Match player entity

- 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

Figure 16: Foul entity

- 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

Figure 17: Card entity

- 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

Figure 18: Goal entity

- 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

Figure 19: Match entity

- 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

Figure 20: Referee entity

- 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

Figure 21: Stadium entity

- 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

Figure 22: Manager entity

- 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

Player N Play for

Club

Figure 23: Player – Club Relationship

- 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

Figure 24: Manager – Club Relationship

- 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

Figure 25: Player – MatchPlayer - Match Relationship

- 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

Figure 26: MatchPlayer – Foul – Card- Goal Relationship

- 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

Figure 27: Stadium – Club - Match Relationship

- 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

Match N take charge of

Referee

Figure 28: Match - Referee Relationship

- 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

Following these steps about for my entity, I have the result:

- Club (ClubID, ClubName) has ClubID as Primary key.

- Player (PlayerID, PlayerName, Nationality, DOB, Height, Position, ShirNo) has

PlayerID as Primary key.

- MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running distances)

has ID as Primary key.

- Manager (ManagerID, Name, Nationality) has ManagerID as Primary key.

- Stadium (StadiumID, Name, Address, Capacity) has StadiumID as Primary key.

- Referee (RefereeID, Name, Nationality, Year of experinces) has RefereeID as Primary

key.

- Foul (ID, Type) has ID as Primary key.

- Card (ID, Color) has ID as Primary key.

- Goal (GoalID, Minute, Offset, Type) has GoalID as Primary 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.

Following the step above, I have the result:

- Match (Date, Status, HostID, GuestID) has primary key is combine of (Date, HostID,

GuestID) (HostID and GuestID are reference key from Club)

III. Step 3: Sub – entities handling:


There is no sub-entity in my ERD so no need to do this steps.

IV. Step 4: 1 – N (1 to many) relationships handling:

- On the many – relationship relation of the relationship, add its foreign keys refers to the

keys of the 1 – relationship relation of the relationship.

- The 1 – N (1 to many) relationships:

 Player (1) – be – Match Player (N)

 Add foreign key PlayerID from Player to Match Player

 MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running

distances, PlayerID)

 Match Player (N) – play in – Match (1):

 Add foreign key (HostID, GuestID, Date) from Match to Match Player

 MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running

distances, PlayerID, HostID, GuestID, Date)

Page 36
 Match Player(1) – Commit / Receive – Foul (N):

 Add foreign key CommitBy, ReceiveBy reference to ID from Match Player to Foul

 Foul (ID, Type, CommitBy, ReceiveBy)

 Foul (N) – Receive – Card (1)

 Add foreign key CardID reference to ID from Card to Foul

 Foul (ID, Type, CommitBy, ReceiveBy, CardID)

 Match Player (1) – Score / Assist – Goal (N)

 Add foreign key ScoreBy, AssistBy reference to ID from Match Player to Goal

 Goal (GoalID, Minute, Offset, Type, ScoreBy, AssistBy)

 Match – take charge by – Referee

 Add foreign key RefereeID reference to RefereeID from Referee to Match

 Match (Date, Status, HostID, GuestID, RefereeID)

V. Step 5: 1 – 1 relationship handling:

- Choose a key from one entity and add it to other entity as foreign key.

- 1 – 1 relationship:

 Club – owned – Stadium

 Add StadiumID reference to StadiumID from Stadium to Club

 Club (ClubID, ClubName, StadiumID)

 Match Player – sub by – Match Player

Page 37
VI. Step 6: Many to many (M - N) relationships handling:
- Steps:

 Create a new table to represent the relationship

 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:

 Player – play for – Club

 Create a new table named Player_Club with attributes from relationship attributes.

 Player_Club (StartDate, EndDate, Salary)

 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

combination of (PlayerID, ClubID)

 Manager – manage – Club

 Create a new table named Manager_Club with attributes from relationship attributes.

 Manager_Club(StartDate, EndDate)

 Add ManagerID reference to ManagerID from Manager, ClubID reference to

ClubID from Club to Manager_Club

 Manager_Club (ManagerID, ClubID, StartDate, EndDate) has primary key is the

combination of (ManagerID, ClubID)

VII. Muli – part and multi – value handling:


- Multi – part attribute: none.

- Multi – value attribute: none.

Page 38
E. Logical Design
I. Relational Schema
List of relations in the database logical design:

- Club (ClubID, ClubName, StadiumID)

- Player (PlayerID, PlayerName, Nationality, DOB, Height, Position)

- Player_Club (PlayerID, ClubID, StartDate, EndDate, Salary, ShirtNo)

- Manager (ManagerID, Name, Nationality)

- Manager_Club (ManagerID, ClubID, StartDate, EndDate)

- MatchPlayer (ID, Shot on target, Pass success, Aerials won, Tackles, Running distances,

PlayerID, HostID, GuestID, Date)

- Match (HostID, GuestID, Date, Status, RefereeID)

- Foul (ID, Type, CommitBy, ReceiveBy, CardID)

- Card (ID, Color)

- Goal (GoalID, Minute, Offset, Type, ScoreBy, AssistBy)

- Stadium (StadiumID, Name, Address, Capacity)

- Referee (RefereeID, Name, Nationality, Year of experinces)

Page 39
II. Database Diagram

Figure 29: Logical Design

Page 40
III. Table Analysis
1. Stadium:

Attributes Data type Allow null

StadiumID (Primary Key) INT No

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

Attributes Data type Allow null

PlayerID (Primary Key) INT No

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.

CONSTRAINT Player_CHK CHECK (Position IN


('Goalkeeper', 'Defender', 'Midfielder', 'Forward'))

Page 42
3. Referee

Attributes Data type Allow null

RefereeID (Primary Key) INT No

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.

CONSTRAINT Referee_CHK CHECK (YearOfExp >= 0)

Page 43
4. Card

Attributes Data type Allow null

ID (Primary Key) INT No

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

Attributes Data type Allow null

ManagerID (Primary Key) INT No

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

Attributes Data type Allow null

ClubID (Primary Key) INT No

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.

CONSTRAINT Club_FK_Stadium FOREIGN KEY (StadiumID)


REFERENCES Stadium(StadiumID)

Page 45
7. Player_Club

Attributes Data type Allow null

PlayerID (Primary Key) INT No

ClubID (Primary Key) INT No

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

CONSTRAINT Player_Club_FK_Player FOREIGN KEY


(PlayerID) REFERENCES Player(PlayerID)
CONSTRAINT Player_Club_FK_Club FOREIGN KEY
(ClubID) REFERENCES Club(ClubID)
 The ShirtNo must be a postitive integer, the EndDate must greater than
StartDate and Salary must greater than zero:
CONSTRAINT Player_Club_CHK CHECK (ShirtNo >= 0 AND
EndDate > StartDate AND Salary > 0)

Page 46
8. Manager_Club

Attributes Data type Allow null

ManagerID (Primary Key) INT No

ClubID (Primary Key) INT No

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

CONSTRAINT Manager_Club_PK PRIMARY KEY (ManagerID,


ClubID)

 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

Attributes Data type Allow null

HostID (Primary Key) INT No

GuestID (Primary Key) INT No

Date (Primary Key) DATE No

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

CONSTRAINT Match_FK_HostClub FOREIGN KEY (HostID)


REFERENCES Club(ClubID)
CONSTRAINT Match_FK_GuestClub FOREIGN KEY
(GuestID) REFERENCES Club(ClubID)
CONSTRAINT Match_FK_Referee FOREIGN KEY
(RefereeID) REFERENCES Referee(RefereeID)

 The status of a match can only one of the values: Scheduled, Playing, Finished,
Postponed. So I added a CHECK constraint

CONSTRAINT Match_CHK CHECK (Status IN


('Scheduled', 'Playing', 'Finished', 'Postponed'))

Page 48
10. MatchPlayer

Attributes Data type Allow null

ID (Primary Key) INT No

isMain BIT No

PlayerID INT No

HostID INT No

GuestID INT No

Date DATE No

SubBy INT Yes

SubTime INT Yes

 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

CONSTRAINT MatchPlayer_FK_MatchPlayer FOREIGN KEY


(SubBy) REFERENCES MatchPlayer(ID)

Page 49
11. Foul

Attributes Data type Allow null

ID (Primary Key) INT No

Type NVARCHAR(100) No

CommitBy INT No

ReceiveBy INT Yes

CardID INT Yes

 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

Attributes Data type Allow null

GoalID (Primary Key) INT No

Minute NVARCHAR(100) No

Offset INT No

Type NVARCHAR(10) No

ScoreBy INT No

AssistBy INT Yes

 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

CONSTRAINT Goal_FK_ScorePlayer FOREIGN KEY


(ScoreBy) REFERENCES MatchPlayer(ID)
CONSTRAINT Goal_FK_AssistPlayer FOREIGN KEY
(AssistBy) REFERENCES MatchPlayer(ID)
 The score minute must be positive integer in between 1 and 90. I assume that a
goal type only receives one of three values: Direct, Own goal and Penalty. So I
added a CHECK constraint to check for valid data
CONSTRAINT Goal_CHK CHECK (Minute >=1 and Minute
<= 90 and Type IN ('Direct', 'Own goal',
'Penalty'))

Page 51
IV. Database statements used to create table
---CREATE DATABSE---
CREATE DATABASE PREMIER_LEAGUE
USE PREMIER_LEAGUE

1. Stadium table

CREATE TABLE Stadium (


StadiumID INT PRIMARY KEY,
Name NVARCHAR(150) NOT NULL,
Address NVARCHAR(200) NOT NULL,
Capacity INT NOT NULL
)

2. Player table

CREATE TABLE Player (


PlayerID INT PRIMARY KEY,
PlayerName NVARCHAR(50) NOT NULL,
Nationality NVARCHAR(50) NOT NULL,
DOB DATE NOT NULL,
Height INT NOT NULL,
Position NVARCHAR(10) NOT NULL,

CONSTRAINT Player_CHK CHECK (Position IN


('Goalkeeper', 'Defender', 'Midfielder', 'Forward'))
)

3. Referee table

CREATE TABLE Referee (


RefereeID INT PRIMARY KEY,
Name NVARCHAR(50) NOT NULL,
Nationality NVARCHAR(50) NOT NULL,
YearOfExp INT NOT NULL,

CONSTRAINT Referee_CHK CHECK (YearOfExp >= 0)


)

Page 52
4. Card table

CREATE TABLE Card (


ID INT PRIMARY KEY,
Color NVARCHAR(6) NOT NULL
CONSTRAINT Card_CHK CHECK (Color IN ('Red',
'Yellow'))
)

5. Manager table

CREATE TABLE Manager (


ManagerID INT PRIMARY KEY,
Name NVARCHAR(50) NOT NULL,
Nationality NVARCHAR(50) NOT NULL
)

6. Club table

CREATE TABLE Club (


ClubID INT PRIMARY KEY,
ClubName NVARCHAR(50) NOT NULL,
StadiumID INT NOT NULL,
CONSTRAINT Club_FK_Stadium FOREIGN KEY
(StadiumID) REFERENCES Stadium(StadiumID)
)

7. Player_Club table

CREATE TABLE Player_Club (


PlayerID INT NOT NULL,
ClubID INT NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
Salary FLOAT NOT NULL,
ShirtNo INT NOT NULL
CONSTRAINT Player_Club_PK PRIMARY KEY
(PlayerID, ClubID),
CONSTRAINT Player_Club_FK_Player FOREIGN
KEY (PlayerID) REFERENCES Player(PlayerID),
CONSTRAINT Player_Club_FK_Club FOREIGN KEY
(ClubID) REFERENCES Club(ClubID),
CONSTRAINT Player_Club_CHK CHECK (ShirtNo
>= 0 AND EndDate > StartDate AND Salary > 0)
)

Page 53
8. Manager_Club table

CREATE TABLE Manager_Club (


ManagerID INT NOT NULL,
ClubID INT NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL

CONSTRAINT Manager_Club_PK PRIMARY KEY


(ManagerID, ClubID),
CONSTRAINT Manager_Club_FK_Manager FOREIGN KEY
(ManagerID) REFERENCES Manager(ManagerID),
CONSTRAINT Manager_Club_FK_Club FOREIGN KEY
(ClubID) REFERENCES Club(ClubID),
CONSTRAINT Manager_Club_CHK CHECK (EndDate >
StartDate)
)

9. Match table

CREATE TABLE Match (


HostID INT NOT NULL,
GuestID INT NOT NULL,
Date DATE NOT NULL,
Status NVARCHAR(10) NOT NULL,
RefereeID INT NOT NULL

CONSTRAINT Match_PK PRIMARY KEY (HostID,


GuestID, Date),
CONSTRAINT Match_FK_HostClub FOREIGN KEY
(HostID) REFERENCES Club(ClubID),
CONSTRAINT Match_FK_GuestClub FOREIGN KEY
(GuestID) REFERENCES Club(ClubID),
CONSTRAINT Match_FK_Referee FOREIGN KEY
(RefereeID) REFERENCES Referee(RefereeID),
CONSTRAINT Match_CHK CHECK (Status IN
('Scheduled', 'Playing', 'Finished', 'Postponed'))
)

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:

SELECT * FROM Referee

ORDER BY YearOfExp DESC

- Result:

Figure 30: Result of query using order by

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:

SELECT p.PlayerName, c.ClubName, p_c.Salary


FROM Player p
INNER JOIN Player_Club p_c ON p_c.PlayerID =
p.PlayerID
INNER JOIN Club c ON c.ClubID = p_c.ClubID
ORDER BY p_c.Salary DESC

- Result:

Figure 31: Result of query using INNER JOIN

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:

SELECT m.Name, c.ClubName, m_c.StartDate,


m_c.EndDate
FROM Manager m
INNER JOIN Manager_Club m_c
ON m_c.ManagerID = m.ManagerID
INNER JOIN Club c
ON c.ClubID = m_c.ClubID

- Result:

Figure 32: Result of query using INNER JOIN

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:

SELECT PlayerName, Nationality, (YEAR(GETDATE())


- YEAR(DOB)) as [Age]
FROM Player
WHERE (YEAR(GETDATE()) - YEAR(DOB)) > 30

- Result:

Figure 33: Result of query using aggregate function

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:

SELECT YEAR(DOB) as [Year],


COUNT (*) as NumPlayer FROM Player
GROUP BY YEAR(DOB)
HAVING YEAR(DOB) >=1985 AND YEAR(DOB) <= 1995

- Result:

Figure 34: Result of query using GROUP BY and HAVING clause

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:

SELECT result.PlayerID, result.PlayerName,


c.ClubName, result.[Number of Goals] FROM (
SELECT p.PlayerID, p.PlayerName, COUNT (*) as
'Number of Goals' FROM Goal g
INNER JOIN Player p ON p.PlayerID = g.ScoreBy
GROUP BY p.PlayerID, p.PlayerName
) result
INNER JOIN Player_Club p_c ON p_c.PlayerID =
result.PlayerID
INNER JOIN Club c ON c.ClubID = p_c.ClubID

- Result:

Figure 35: Result of query using sub query as relation

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:

SELECT DISTINCT * FROM Player


WHERE PlayerID
IN (SELECT CommitBy FROM Foul)
- Result:

Figure 36: Result of query using sub query in where clause

- 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:

SELECT result.ClubName, s.Name, s.Capacity FROM


(SELECT * FROM Club
WHERE StadiumID
IN (SELECT HostID FROM Match
WHERE Status = 'Finished')) result
INNER JOIN
Stadium s ON s.StadiumID = result.StadiumID
- Result:

Figure 37: Result of query using sub query in where clause

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:

SELECT * FROM Player


WHERE PlayerName like '%in%'

- Result:

Figure 38: Result of query using partial matching in WHERE clause

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:

SELECT (SELECT PlayerName FROM Player WHERE


PlayerID = mp2.PlayerID) as 'OUT',
(SELECT PlayerName FROM Player WHERE PlayerID =
mp1.PlayerID) as 'IN',
mp2.SubTime as 'Minute' FROM MatchPlayer mp1
INNER JOIN MatchPlayer mp2 ON mp2.SubBy = mp1.ID

- Result:

Figure 39: Result of query using self - join

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:

Figure 40: Store procedure

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;

SELECT @Date = Date, @HostID = HostID, @GuestID =


GuestID FROM inserted

SELECT @COUNT = SUM (CASE WHEN SubBy IS NULL THEN 0


ELSE 1 END) FROM MatchPlayer
WHERE Date = @Date AND HostID = @HostID AND GuestID =
@GuestID

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

Figure 41: Trigger

Page 66

You might also like