Related
I'm getting duplicate data when trying to use the select statements, I have 9 rooms but I'm getting around 50-70 rooms when trying to display them. Help please?
I'm trying to insert data and display it using the select statement.
create table gym (
GymName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table Spa (
spaName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table customer (
CustomerID int primary key,
Firstname varchar(200) not null,
LastName varchar(200) not null,
DOB date not null check (DATEDIFF(year,DOB,getdate ()) > 18) ,
Gender char(4) not null check(Gender ='M' or Gender = 'F'),
Address varchar(200) not null default 'Jordan',
spaName VARCHAR(200) foreign key references Spa(spaName),
GymName VARCHAR(200) foreign key references gym(GymName),
);
Create table CustomerPhoNo (
CustomerID int foreign key references customer(CustomerID),
PhoneNo bigint not null,
);
create table Room (
roomNo int primary key,
Availability char(4) not null,
NoOfBeds int not null,
Rate int not null,
CheckIn date,
CheckOut date,
Price Decimal not null,
Breakfast char(4),
CustomerID int foreign key references customer(CustomerID),
);
create table LocationOfRoom (
roomNo int foreign key references Room(roomNo),
seaview char(4),
Location varchar(20) not null,
);
create table RoomType (
roomNo int foreign key references Room(roomNo),
familyRoom char(4),
doubleRoom char(4),
singleRoom char(4),
);
create table Gservice (
GymName VARCHAR(200) foreign key references gym(GymName),
Service VARCHAR(500) not null,
MachineType VARCHAR(500) not null,
);
create table PaymentCard (
CardID int primary key,
issueDate date not null,
Expirydate date not null,
CustomerID int foreign key references customer(CustomerID),
);
insert into customer values (325,'Mohammad','Alasharan','06-04-1984','M','Amman', 'BeautySpa', 'StrongBody')
insert into customer values (348,'John','Shelby','10-18-1998','M','Birmingham', 'LushLife', 'SilverGym')
insert into customer values (495,'Thomas','Hoffman','04-26-1968','M','Johannesburg', 'RelaxationTherapy', 'SilverGym')
insert into customer values (194,'Anne','Frank','07-22-2001','F','Frankfurt', 'BeautySpa', 'StrongBody')
insert into customer values (628,'Katie','Swan','02-10-1997','F','New South Wales', 'LushLife', 'FitnessHeroes')
insert into customer values (246,'Mahmoud','Alkutaifan','04-21-1994','M','Amman', 'BeautySpa', 'FitnessHeroes')
insert into customer values (864,'Karl-Heinz','Rummenigge','09-25-1955','M','Lippstadt', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (824,'Dennis','Law','09-21-1979','M','london', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (463,'Carles','Puyol','06-17-1973','M','madrid', 'LushLife', 'FitnessHeroes')
insert into Room values (124,'yes','1','4',null,null,'30','yes',null)
insert into Room values (135,'no','2','5','05-06-2022','05-09-2022','55','yes',495)
insert into Room values (121,'yes','1','3',null,null,'40','yes',null)
insert into Room values (139,'no','3','4','05-10-2022','05-14-2022','110','no',194)
insert into Room values (131,'no','3','3','05-18-2022','05-22-2022','130','yes',348)
insert into Room values (136,'no','4','4','04-14-2022','04-24-2022','120','yes',194)
insert into Room values (179,'yes','4','5',null,null,'95','no',null)
insert into Room values (138,'no','3','3','04-02-2022','04-06-2022','75','no',246)
insert into Room values (146,'no','3','5','05-10-2022','05-14-2022','80','yes',864)
insert into LocationOfRoom values (124,'no','south')
insert into LocationOfRoom values (135,'yes','north')
insert into LocationOfRoom values (121,'yes','south')
insert into LocationOfRoom values (139,'no','north')
insert into LocationOfRoom values (131,'no','East')
insert into LocationOfRoom values (136,'yes','west')
insert into LocationOfRoom values (179,'no','south')
insert into LocationOfRoom values (138,'no','west')
insert into LocationOfRoom values (146,'yes','north')
insert into RoomType values (124,'no','no','yes')
insert into RoomType values (135,'no','yes','no')
insert into RoomType values (121,'yes','no','no')
insert into RoomType values (139,'no','no','yes')
insert into RoomType values (131,'no','no','yes')
insert into RoomType values (136,'no','no','yes')
insert into RoomType values (179,'no','no','yes')
insert into RoomType values (138,'no','yes','no')
insert into RoomType values (146,'no','no','yes')
-- display Total number of customers who booked a single room with sea view option
select count(Firstname)
from LocationOfRoom, customer, RoomType, Room
where seaview='yes' and singleRoom='yes'
Any help would be greatly appreciated, thank you in advance!
Your FROM clause is missing the join condition for each table. In other words you are getting the cartesian product (every combination of rows) of the tables. Even distinct won't help (it will get the wrong answer). Use join conditions to link the keys of each table to each other. I'll leave this an exercise for you to try out, but this should be enough information to help you out.
I believe the solution for your problem is that you need to use DISTINCT:
SELECT COUNT(DISTINCT(Firstname))
FROM LocationOfRoom, customer, RoomType, Room
WHERE seaview='yes' AND singleRoom='yes'
I have tested it and it retrieves 9 Rooms.
I have a lecture attendance database as an uni project.
As one of views, i came up with idea that I could make missed_lectures view with all records of Not attended or Sick attendance types. When I am making this query, it returns 2,5k rows, which is not correct.
Query looks like this
CREATE OR REPLACE VIEW missed_lectures AS
SELECT CONCAT(s.student_name, ' ', s.student_surname) AS "Student", sc.course_title AS "Study course", atp.attendance_type AS "Attendance type", a.record_date AS "Date"
FROM students AS s, study_courses AS sc, attendance_type AS atp, attendance AS a
WHERE
s.student_id=a.student_id AND
sc.course_id=a.course_id AND
a.attendance_type_id=atp.attendance_type_id AND
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendacne_type='Sick') OR
a.attendance_type_id=(SELECT attendance_type_id FROM attendance_type WHERE attendance_type='Not attended')
GROUP BY s.student_name, s.student_surname, sc.course_title, atp.attendance_type, a.record_date;
This is the last query I came up with, but as I mentioned earlier, it returns 2,5k rows with incorrect data.
Can anybody spot the issue here?
EDIT:
table students is
CREATE TABLE students(
student_id serial PRIMARY KEY NOT NULL,
student_name VARCHAR(30) NOT NULL,
student_surname VARCHAR(35) NOT NULL,
matriculation_number VARCHAR(7) NOT NULL CHECK(matriculation_number ~ '[A-Z]{2}[0-9]{5}'),
faculty_id INT NOT NULL,
course INT NOT NULL,
phone_number CHAR(8) CHECK(phone_number ~ '^2{1}[0-9]{7}'),
email VARCHAR(35),
gender VARCHAR(10)
);
sample data:
INSERT INTO students (student_name, student_surname, matriculation_number, faculty_id, course, phone_number, email, gender)
VALUES
('Sandis','Bērziņš','IT19047',7,1,'25404213','sandis.berzins#gmail.com','man'),
('Einārs','Kļaviņš','IT19045',7,1,'24354654','einars.klavins#gmail.com','man'),
('Jana','Lapa','EF18034',8,2,'26224941','lapajana#inbox.lv','woman'),
('Sanija','Bērza','EF18034',8,2,'24543433','berzasanija#inbox.lv','woman'),
('Valdis','Sijāts','TF19034',4,1,'25456545','valdis.sijats#gmail.com','man'),
('Jānis','Bānis','IT17034',7,3,'24658595','banis.janis#inbox.lv','man');
table study_courses is
CREATE TABLE study_courses(
course_id serial PRIMARY KEY NOT NULL,
course_title VARCHAR(55) NOT NULL,
course_code VARCHAR(8) NOT NULL CHECK(course_code ~ '[a-zA-Z]{4}[0-9]{4}'),
credit_points INT
);
sample data:
INSERT INTO study_courses (course_title, course_code, credit_points)
VALUES
('Fundamentals of Law','JurZ2005',2),
('Database technologies II','DatZ2005',2),
('Product processing','PārZ3049',4),
('Arhitecture','Arhi3063',3),
('Forest soils','LauZ1015',4);
Table attendance_type is:
CREATE TABLE attendance_type(
attendance_type_id serial PRIMARY KEY NOT NULL,
attendance_type VARCHAR(15) NOT NULL
);
sample data:
INSERT INTO attendance_type (attendance_type)
VALUES
('Attended'),
('Not attended'),
('Late'),
('Sick');
table attendance is:
CREATE TABLE attendance(
record_id serial PRIMARY KEY NOT NULL,
student_id INT NOT NULL,
course_id INT NOT NULL,
attendance_type_id INT NOT NULL,
lecturer_id INT,
lecture_type_id INT NOT NULL,
audience_id INT NOT NULL,
record_date DATE NOT NULL
);
sample data:
INSERT INTO attendance (student_id, course_id, attendance_type_id, lecturer_id, lecture_type_id, audience_id, record_date)
VALUES
(1,2,1,1,1,14,'20-05-2020'),
(2,2,1,1,1,14,'20-05-2020'),
(6,9,1,13,2,2,'20-05-2020'),
(22,9,2,13,2,2,'20-05-2020'),
(24,9,3,13,2,2,'20-05-2020');
Hoping this will help.
The problem is that OR condition in your WHERE clause.
You have to surround it by parentheses if you're going to do it that way.
However, you're already querying the attendance_type table so you can just use it to filter for those two attendance type conditions.
SELECT
CONCAT(s.student_name, ' ', s.student_surname) AS "Student",
sc.course_title AS "Study course",
atp.attendance_type AS "Attendance type",
a.record_date AS "Date"
FROM
students AS s, study_courses AS sc,
attendance_type AS atp, attendance AS a
WHERE
s.student_id=a.student_id AND
sc.course_id=a.course_id AND
a.attendance_type_id=atp.attendance_type_id AND
-- filter for these two conditions without subqueries
atp.attendance_type in ('Sick','Not attended')
GROUP BY
CONCAT(s.student_name, ' ', s.student_surname), sc.course_title,
atp.attendance_type, a.record_date;
all day I am struggling with oracle exrcises and again I stuck. I need to select last names of boxers with their wins of each weight category.
So I have:
table "boxer" with columns: id, fname, lname, weight
table "fight" with two foreign keys from table boxer (id_boxer1 and id_boxer2) and with one column winner (if boxer1 won then winner will be number 1, if boxer2 won then winner will be number 2)
table "category_weight" with columns: id, min_weight, max_weight, name (of a category)
Example:
CREATE TABLE category_weight(
id INTEGER NOT NULL,
min_weight SMALLINT NOT NULL,
max_weight SMALLINT NOT NULL,
name VARCHAR2(20) NOT NULL
);
ALTER TABLE category_weight ADD CONSTRAINT category_weight_pk PRIMARY KEY ( id );
CREATE TABLE boxer(
id INTEGER NOT NULL,
fname VARCHAR2(20) NOT NULL,
lname VARCHAR2(20) NOT NULL,
weight INTEGER NOT NULL
);
ALTER TABLE boxer ADD CONSTRAINT boxer_pk PRIMARY KEY ( id );
CREATE TABLE fight(
id INTEGER NOT NULL,
winner SMALLINT NOT NULL,
id_category_weight INTEGER NOT NULL,
id_boxer1 INTEGER NOT NULL,
id_boxer2 INTEGER NOT NULL
);
ALTER TABLE fight ADD CONSTRAINT fight_pk PRIMARY KEY ( id );
ALTER TABLE fight
ADD CONSTRAINT boxer_fk FOREIGN KEY ( id_boxer1 )
REFERENCES boxer ( id );
ALTER TABLE fight
ADD CONSTRAINT boxer_fk2 FOREIGN KEY ( id_boxer2 )
REFERENCES boxer ( id );
ALTER TABLE fight
ADD CONSTRAINT categ_weight_fk FOREIGN KEY ( id_category_weight )
REFERENCES category_weight ( id );
INSERT INTO boxer
VALUES ('1', 'Johnny','Johnny','60');
INSERT INTO boxer
VALUES ('2', 'Anthonny','Anthonny','54');
INSERT INTO boxer
VALUES ('3', 'Anonimm','Anonimm','59');
INSERT INTO boxer
VALUES ('4', 'John','Johnowski','71');
INSERT INTO category_weight
VALUES ('1', '1','70','category1');
INSERT INTO category_weight
VALUES ('2', '71','100','category2');
INSERT INTO fight
VALUES ('1','1','1','1','2');
INSERT INTO fight
VALUES ('2','2','1','3','1');
Boxer with ID "1" won two fights in category1, so the result should be:
Lname Category Wins
Johnny category1 2
Here, try this:
SELECT b.lname,
cw.max_weight AS WEIGHT_CLASS,
COUNT(CASE WHEN f.winner = b.id THEN 1 ELSE NULL END) AS WINS
FROM boxer b
INNER JOIN fight f ON b.id = f.id_boxer1 OR b.id = f.id_boxer2
INNER JOIN category_weight cw ON f.id_category_weight = cw.id
GROUP BY b.lname, cw.max_weight
CREATE TABLE Subject_Marks
(
Marks_ID int primary key,
Maths_Score int,
Science_Score int,
Social_Score int,
English_Score int,
SUPW_Score int,
Student_ID int not null
);
INSERT into Subject_Marks VALUES
(1,1001, 50, 99,98,45,57);
NOT ABLE TO JOIN THIS TABLE WITH OTHER TABLE SHOWN BELOW.
CREATE TABLE Student_Data
(
Student_ID int IDENTITY(1001,1) PRIMARY KEY,
Student_Name VARCHAR(20) NOT NULL,
Student_Address VARCHAR(100),
Student_Phone bigint,
Student_Email VARCHAR(30),
college_id int NOT NULL
);
Since Student_ID is the key providing the relationship, you need to use this in a join. So, you need to construct a join like below for SQL Server:
select sd.* , sm.*
from Student_Data sd
inner join Subject_Marks sm on sm.Student_ID = sd.Student_ID
I have to write a query for my database. The query is below.
/* Query 9 – Most Valuable Players
"Who has received at least 2 MVP awards?"
Produce a query to display the full name and number of MVP awards of any players who have been awarded the MVP in at least 2 races.
Make sure that races where no MVP was awarded are not included in the results, and order your results by the number of MVP awards in descending order.
Using your race view in this query is recommended.
Hint: Use HAVING to limit the results to players with an MVP count of at least 2.
I've tried it using this code:
CREATE VIEW playerView1
AS
select
player.id, player.firstName + ' ' + player.surname AS 'Full Name', race.mvp
from
player
JOIN
race ON player.team = race.team
GO
SELECT playerView1.[Full Name]
From playerView1
GROUP BY [Full Name]
HAVING (playerView1.mvp) >1
and also tried
SELECT
player.firstName + ' ' + player.surname AS 'Full_name', raceView.mvp AS 'MVP Number',
raceView.mvp_name AS 'MVP Name'
FROM
raceView
JOIN
player ON raceView.mvp_name = player.firstName
WHERE
raceView.mvp > 1
And no luck. Any ideas on where I've gone wrong? and possibly a fix?
One of the errors I came across using the first query was
Msg 8121, Level 16, State 1, Line 4
Column 'playerView1.mvp' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
Below is my entire database script which include create, populate and view before been able to do the query which results in my issue.
IF DB_ID ('Assignment2') IS NOT NULL
BEGIN
DROP DATABASE Assignment2;
END
/* Now create new database*/
CREATE DATABASE Assignment2;
GO
/* Make system use new database */
USE Assignment2;
/* Begin Creating tables */
/** Create Course Table **/
PRINT 'Creating table course.';
CREATE TABLE course (
id INT IDENTITY, -- [CourseID] [int] IDENTITY(1,1) NOT NULL,
name VARCHAR(50), -- [CourseName] [varchar](50) NULL,
passingScore NUMERIC(18,0), -- [PassingScore] [numeric](18, 0) NOT NULL,
CONSTRAINT course_pk PRIMARY KEY (id),
CONSTRAINT passingScore CHECK (passingScore BETWEEN 0 AND 100)
);
/** Create RaceType Table**/
PRINT 'Creating table Race Type.'
CREATE TABLE raceType (
id INT IDENTITY, -- [RaceTypeID] [int] IDENTITY(1,1) NOT NULL,
name VARCHAR(25) NOT NULL, -- [RaceTypeName] [varchar](25) NOT NULL,
CONSTRAINT raceType_pk PRIMARY KEY (id),
CONSTRAINT raceType_unique UNIQUE (name)
);
/** Create 'Teams' Table */
PRINT ' Creating table called Teams'
CREATE TABLE team (
id INT IDENTITY, -- [TeamID] [int] IDENTITY (1,1) NOT NULL,
name VARCHAR(25) NOT NULL, -- [TeamName] [varchar] (25) NOT NULL,
biography TEXT, -- [Biography] [text] NULL,
hyperlink VARCHAR(max), -- [Hyperlink] [varchar] (max) NULL,
CONSTRAINT team_pk PRIMARY KEY (id),
CONSTRAINT team_unique UNIQUE (name)
);
/** Create "Players" Table**/
PRINT ' Creating table called Players'
CREATE TABLE player (
id INT IDENTITY, -- [PlayerID] [int] IDENTITY(1,1) NOT NULL,
firstName VARCHAR(50) NOT NULL, -- [FirstName] [varchar](50) NOT NULL,
surname VARCHAR(50) NOT NULL, -- [Surname] [varchar](50) NOT NULL,
coach INT, -- fk1 [CoachID] [int] NULL,
team INT, -- fk2 [TeamID] [int] NULL,
CONSTRAINT player_pk PRIMARY KEY (id),
CONSTRAINT player_fk1 FOREIGN KEY (team) REFERENCES team (id),
CONSTRAINT player_fk2 FOREIGN KEY (coach) REFERENCES player (id)
);
/** Create "Races" Table **/
PRINT ' Creating table called Races'
CREATE TABLE race (
id INT IDENTITY, -- [RaceID] [int] IDENTITY(1,1) NOT NULL,
dateOfRace DATETIME NOT NULL, -- [DateOfRace] [datetime] NOT NULL,
raceType INT NOT NULL, -- [RaceTypeID] [int] NOT NULL,
course INT NOT NULL, -- [CourseID] [int] NOT NULL,
team INT NOT NULL, -- [TeamID] [int] NOT NULL,
observer INT NOT NULL, -- [ObserverID] [int] NOT NULL,
mvp INT NULL, -- [MvpPlayerID] [int] NULL,
finalScore INT NOT NULL, -- [FinalScore] [int] NOT NULL,
pointsPenalised INT NOT NULL, -- [PointsPenalised] [int] NOT NULL,
CONSTRAINT race_pk PRIMARY KEY (id),
CONSTRAINT race_fk1 FOREIGN KEY (raceType) REFERENCES raceType(id),
CONSTRAINT race_fk2 FOREIGN KEY (course) REFERENCES course(id),
CONSTRAINT race_fk3 FOREIGN KEY (team) REFERENCES team(id),
CONSTRAINT race_fk4 FOREIGN KEY (observer) REFERENCES player(id),
CONSTRAINT race_fk5 FOREIGN KEY (mvp) REFERENCES player(id)
);
GO
/** End*/
The populate script
/** Begin Populating "Course" table*/
PRINT 'Populating Course Table'
INSERT INTO course (name,passingScore)
VALUES ('Easy Course','80');
INSERT INTO course (name,passingScore)
VALUES ('Medium Course','70');
INSERT INTO course (name,passingScore)
VALUES ('Hard Course','60');
/** Begin Populating "RaceType" Table */
PRINT 'Populating RaceType Table '
INSERT INTO raceType (name)
VALUES ('Ranked')
INSERT INTO raceType (name)
VALUES ('Practise')
/** Begin Populating "Teams" Table */
PRINT ' Populating Teams Table'
INSERT INTO team (name)
VALUES ('Team BMW');
INSERT INTO team (name)
VALUES ('Team Porsche');
INSERT INTO team (name)
VALUES ('Team Mercedez');
INSERT INTO team (name)
VALUES ('Team AMartin');
INSERT INTO team (name)
VALUES ('Team Audi');
INSERT INTO player (firstName, surname)
VALUES ('hoger','amedi');
INSERT INTO player (firstName, surname, coach, team)
VALUES (' Lloyd', 'Banks', 1, 1);
INSERT INTO player (firstName, surname)
VALUES ('Silav', 'Govand');
INSERT INTO player (firstName, surname, coach, team)
VALUES ('hell', 'razor', 2, 2);
INSERT INTO player (firstName, surname, coach, team)
VALUES ( 'Alden', 'Padilla', 3, 1);
INSERT INTO player (firstName, surname)
VALUES ( 'Sina', 'Parker');
INSERT INTO player (firstName, surname, coach, team)
VALUES ( 'Lyle', ' Burks', 4, 2);
INSERT INTO player (firstName, surname, coach, team)
VALUES ('Rhona', 'Anthony', 5, 3);
INSERT INTO player (firstName, surname, team)
VALUES ('Seelie', 'Harper', 5);
INSERT INTO player (firstName, surname, coach, team)
VALUES ('Harper', 'Leonards', 6, 4)
INSERT INTO player (firstName, surname, coach, team)
VALUES ('jack', 'Merril', 7, 5)
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-03 06:01:49','53','4','2','1','4','2','1');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-11-25 09:31:26','73','5','2','2','1','3','2');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-03 19:36:34','52','1','1','1','5','4','3');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-10 20:07:11','51','4','2','3','2','5','2');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-11-15 19:19:33','83','5','2','1','3','6','1');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-27 02:32:09','53','1','2','3','5','7');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-24 10:31:53','51','3','1','1','4','8');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-19 15:17:32','70','2','1','2','5','9');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-12-08 18:00:51','59','2','1','3','1','10');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-12-09 19:55:53','67','5','2','3','5','10');
Select *
From player;
Select *
From team;
Select *
From raceType;
Select *
From course;
Select *
From race;
the View script
USE Assignment2;
GO
PRINT 'Creating Player View'
GO
CREATE VIEW playerView AS
SELECT player.id, player.firstName + ' ' + player.surname AS 'Full name', player.team, team.name, player.coach, coach.firstName, coach.surname
FROM player
LEFT OUTER JOIN team
ON player.team = team.id
LEFT OUTER JOIN player as coach
ON player.coach = coach.id;
GO
/*
Create a view which shows the following details of all races:
• All of the columns in the race table
• The name of the race type, course and team involved in the race
• The full name of the player observing the race and the full name of the MVP (if applicable)
• A calculated column with an alias of “unpenalised_score”, which adds the points penalised to the final score
Creating this view requires a select statement using multiple joins and concatenation of names.
Make sure that you use the appropriate type of join to ensure that races without MVPs are still included in the results.
*/
-- Write your Race View here
PRINT 'Creating Race View'
GO
CREATE VIEW raceView AS
SELECT race.id, race.dateOfRace, race.raceType, raceType.name AS raceTypeName, race.course, course.name AS courseName, race.team, team.name AS teamName, race.observer, obs.firstName + ' ' + obs.surname AS observer_name, race.mvp, mvp.firstName + ' ' + mvp.surname AS mvp_name, race.pointsPenalised, race.finalScore + race.pointsPenalised AS unpenalised_score, race.finalScore
FROM race
INNER JOIN raceType
ON race.raceType = raceType.id
INNER JOIN course
ON race.course = course.id
INNER JOIN team
ON race.team = team.id
LEFT OUTER JOIN player AS mvp
ON race.mvp = mvp.id
LEFT OUTER JOIN player AS obs
ON race.observer = obs.id;
GO
SELECT *
FROM playerView
SELECT *
FROM raceView
you need to use COUNT
select player.id,
player.firstName + ' ' + player.surname AS [Full Name],
COUNT(*)
from player JOIN race
ON player.team = race.team
GROUP BY id, player.firstName + ' ' + player.surname
HAVING COUNT(*) >= 2
UPDATE 1
SELECT MVP_NAME, COUNT(*) TotalMVP
FROM raceView
WHERE MVP IS NOT NULL
GROUP BY MVP_NAME
HAVING COUNT(*) >= 2
ORDER BY TotalMVP DESC;
SQLFiddle Demo