Creating a view in Sql with connected tables - sql

I am trying to create a view off of two different tables. Basically I have 2 tables
(MatchStats- Holds all of the fixture information)
(Team - Holds all of the team information)
Here is the code for both tables
Team
CREATE TABLE TEAM
(
TeamID int NOT NULL,
TeamName varchar(30) NOT NULL,
Teamlocale varchar(30) NOT NULL,
CONSTRAINT pkTeamID PRIMARY KEY (TeamID),
)
MatchStats
CREATE TABLE MATCHSTATS
(
MatchStatsID int NOT NULL,
Team1ID int NOT NULL,
Team1Goals int NOT NULL,
Team2ID int NOT NULL,
Team2Goals int NOT NULL,
RefereeID int NOT NULL,
PitchID int NOT NULL,
sessionTime varchar(20) NOT NULL,
sessionDate varchar(20) NOT NULL,
CONSTRAINT pkMatchStatsID PRIMARY KEY (MatchStatsID),
CONSTRAINT fkTeam1ID FOREIGN KEY (Team1ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkTeam2ID FOREIGN KEY (Team2ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkReferee FOREIGN KEY (RefereeID) REFERENCES REFEREE(RefereeID),
CONSTRAINT fkpitchID FOREIGN KEY (PitchID) REFERENCES Pitch(pitchID),
)
I am trying to create a view that will display the fixture information but use the team name instead of ID. I have been researching and looking at previous questions online and I just cant seem to understand how to do it
This is what I have managed to come up with
CREATE VIEW FIXTUREHSITORY AS
SELECT m.Team1ID, m.Team1Goals, m.Team2ID, m.Team2Goals, T.TeamName
from MATCHSTATS as m
JOIN TEAM as t ON t.TeamID on
Overall I am trying to create a report that looks like this
Team 1 Name | Goals | Team 2 Name | Goals
Sorry if I seem vague and thanks in advance

A solution to your problem:
MSSQL
CREATE VIEW FIXTUREHISTORY AS
SELECT t1.TeamName Team1Name,
m.Team1Goals Team1Goals,
t2.TeamName Team2Name,
m.Team2Goals Team2Goals
from MATCHSTATS as m
INNER JOIN TEAM as t1 ON t1.TeamID = m.Team1ID
INNER JOIN TEAM as t2 ON t2.TeamID = m.Team1ID
Demo Link:
http://sqlfiddle.com/#!18/34883/1

Related

SQL, Delete Records Based On Related Fields In Other Table

I have a SQL table based on hotel data. I have two tables and a bridge table to relate them. I'm still learning so I'm sure some of this is not ideal or has potential risks.
Guest Table
CREATE TABLE Guest
(
Guest_ID INT PRIMARY KEY IDENTITY (1, 1),
GuestName NVARCHAR(60) NOT NULL,
Street NVARCHAR(50) NOT NULL,
City NCHAR(30) NOT NULL,
[State] CHAR(2) NOT NULL,
CONSTRAINT [State.State]
FOREIGN KEY ([State]) REFERENCES [State]([State]),
Zip CHAR(5) NOT NULL,
Phone VARCHAR(15) NOT NULL
);
Room Table
CREATE TABLE Room
(
Room_ID SMALLINT PRIMARY KEY,
Room_Type_ID SMALLINT NOT NULL,
CONSTRAINT Room_Type_ID
FOREIGN KEY (Room_Type_ID) REFERENCES Room_Type([Type_ID]),
Amenity_Type_ID SMALLINT NOT NULL,
CONSTRAINT Amenity_Type_ID
FOREIGN KEY (Amenity_Type_ID) REFERENCES Amenity_Type([Type_ID])
);
Bridge Table (Reservations)
CREATE TABLE Guest_Bridge_Rooms
(
Guest_ID INT NOT NULL,
CONSTRAINT Guest_ID
FOREIGN KEY (Guest_ID) REFERENCES Guest(Guest_ID),
Room_ID SMALLINT NOT NULL,
CONSTRAINT Room_ID
FOREIGN KEY (Room_ID) REFERENCES Room(Room_ID),
Date_Start DATE NOT NULL,
Date_End DATE NOT NULL,
Occ_Adults SMALLINT NOT NULL,
Occ_Children SMALLINT NOT NULL,
Price_Total DECIMAL(13,2) NOT NULL
);
Now with these tables, I would like to write a script to DELETE all rows where a reservation (bridged table) has a specific guest NAME by somehow relating the given Guest_ID to its GuestName in the related table. I could simply use Guest_ID but that is not the goal here.
For example something like
DELETE FROM Guest_Bridge_Rooms
WHERE Guest[ID].GuestName = 'John Doe';
Is there a simple way to do this?
You can use a subquery:
DELETE FROM Guest_Bridge_Rooms
WHERE Guest_ID = (SELECT g.Guest_Id FROM Guests g WHERE g.GuestName = 'John Doe');
Note: The exact syntax might vary, depending on the database. This also assumes that GuestName is unique in Guests.

How to get the highest appearance value in one table, from another table?

So I have 3 tables referencing cars, assurance and accident.
I want to know the brand of vehicles who had the most accidents, compared to others.
I have tried a lot of ways to that, but mostly i only get or all the brands returned or the brand of the car that was registered the most, not the one that had most accidents
These are my tables
create table car(
n_veic bigint not null,
matric varchar(15) not null,
pais_matric text not null,
n_pess bigint not null,
tipo text not null,
cor text not null,
brand text not null,
modelo varchar(15),
primary key(n_veic),
unique(matric),
foreign key (n_pess) references pessoa(n_pess)
);
create table ensurance(
apolice bigint not null,
segurado bigint not null,
car bigint not null,
datai date not null,
dataf date not null,
cobertura numeric(10,2) not null,
primary key(apolice),
unique(segurado, veiculo),
foreign key (segurado) references pessoa(n_pess),
foreign key (car) references car(n_veic)
);
create table accident(
n_acid bigint not null,
pess_segura bigint not null,
veic_seguro bigint not null,
data date not null,
local varchar(255) not null,
descr text not null,
primary key(n_acid),
unique(n_acid, veic_seguro),
foreign key (pess_segura,veic_seguro) references ensurance(segurado, car)
This is what i tried
SELECT marca
FROM veiculo NATURAL JOIN acidente
GROUP BY marca
HAVING count (distinct n_veic)>=ALL
(SELECT count (distinct n_veic)
FROM veiculo NATURAL JOIN acidente
GROUP BY marca);
I think the logic is:
select c.marca, count(*) as num_acidentes
from acidente a join
car c
on a.veic_seguro = c.n_veic
group by c.marca
order by num_acidentes desc;
You can use fetch first 1 row only -- or whatever is appropriate for your database -- to get only one row.
Try this-
Note:
1. Try to avoid NATURAL JOIN and use specific column reference.
2. Rethink DISTINCT for count is really necessary or not.
SELECT TOP 1 marca, COUNT(DISTINCT n_veic)
FROM veiculo
NATURAL JOIN acidente
GROUP BY marca
ORDER BY COUNT(DISTINCT n_veic) DESC

How do i fill my table with data from 3 different tables?

So I am working on a football world cup database. These are my important tables:
CREATE TABLE Countries(
Cid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE
);
CREATE TABLE Stadiums(
Sid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE,
Cid INT REFERENCES Countries NOT NULL
);
CREATE TABLE Groups(
Gid SERIAL PRIMARY KEY,
Name VARCHAR(64) NOT NULL,
TYear SMALLINT REFERENCES Tournaments NOT NULL
);
CREATE TABLE Teams(
Tid SERIAL PRIMARY KEY,
Cid INT REFERENCES Countries NOT NULL,
Gid INT REFERENCES Groups NOT NULL
);
CREATE TABLE Matches(
Mid INT PRIMARY KEY,
HomeTid INT REFERENCES Teams NOT NULL,
VisitTid INT REFERENCES Teams NOT NULL,
HomeScore SMALLINT NOT NULL,
VisitScore SMALLINT NOT NULL,
MatchDate DATE NOT NULL,
MatchType VARCHAR(64) NOT NULL,
Sid INT REFERENCES Stadiums NOT NULL
);
CREATE TABLE tempmatches(
year INTEGER,
host_country VARCHAR(255),
match_id INTEGER,
type VARCHAR(255),
date DATE,
location1 VARCHAR(255),
team1 VARCHAR(255),
team2 VARCHAR(255),
score1 INTEGER,
score2 INTEGER
);
so my current problem is that I need to populate the columns HomeTid and VisitId of the Matches table with the tid's from the team's table that corresponds with the country of that team from the countries table but I'm not sure how to do that. I tried a few queries but none of them seemed to work. Has anyone an idea on how to solve this?
Using JOIN keyword you can combine 2 tables data.
Here, in this case, you have to use 3-way join.
Eg:
3-way JOIN can be used in this way:
SELECT * FROM table1 JOIN table2 ON table1.col1=table2.col2 JOIN table3 ON table3.col3=table.col1;
Here the 2 tables will get joined based on the columns mentioned after the "ON" keyword.
Here is a reference link in which JOIN is explained clearly
https://www.w3schools.com/sql/sql_join.asp
Use JOIN operation. In SQL it helps to combine several tables(queries) in one

SQL Query that displays the number of athletes that have competed in at least ten different places(locations)

I'm building a query based on the fact that they have competed in ten or more places. Note that it does not matter how many sports or competitions they competed in, just how many places they have competed in.
CREATE TABLE Gender (
gender CHAR(1),
description VARCHAR(10),
PRIMARY KEY (gender));
CREATE TABLE People (
ID INT,
name VARCHAR(50),
gender CHAR(1),
height FLOAT,
PRIMARY KEY (ID),
FOREIGN KEY (gender) REFERENCES Gender (gender));
CREATE TABLE Sports (
ID INT,
name VARCHAR(50),
record FLOAT,
PRIMARY KEY (ID),
UNIQUE (name));
CREATE TABLE Competitions (
ID INT,
place VARCHAR(50),
held DATE,
PRIMARY KEY (ID));
CREATE TABLE Results (
peopleID INT NOT NULL,
competitionID INT NOT NULL,
sportID INT NOT NULL,
result FLOAT,
PRIMARY KEY (peopleID, competitionID, sportID),
FOREIGN KEY (peopleID) REFERENCES People (ID),
FOREIGN KEY (competitionID) REFERENCES Competitions (ID),
FOREIGN KEY (sportID) REFERENCES Sports (ID));
If anyone can help me with this it would be much appreciated!
As commented by Brad, you can use a simple aggregated query that JOINs table People with Results, with a HAVING BY clause to filter on the number of competitions each person participated to. It seems like you don’t need to bring in any other table to achieve your goal.
SELECT
p.ID,
p.Name
FROM
People p
Results r ON r.peopleID = p.ID
GROUP BY
p.ID,
p.Name
HAVING COUNT(*) >= 10

Using foreign keys with multiple tables

I have a problem with creating a database. My fictional problem is to create database for tracking volleyball games. It should contain information about players (team they play in, one player can play only in one team), and played games( every game contains 6 players in each team).
I wanted to create following tables :
Player(Id P,Name,Surname,Team_Name F) ;
Team(Team_Name P,Coach);
Game(Date, Team1 F,Team2 F,Player1_Team1 F,...Player2_Team2 F,Player1_Team2 F,...,Player2_Team2 F).
I wanted that Team1 and Team2 are foreign keys Team_Name from Team table. Here is my attempt, I get that foreign key is incorrectly formed. I will be very glad for help.
CREATE TABLE Team (
Team_Name varchar(20) NOT NULL,
Coach varchar(20) NOT NULL,
CONSTRAINT Team_pk PRIMARY KEY (Team_Name)
);
CREATE TABLE Game (
id int NOT NULL,
Data date NOT NULL,
Team1 varchar(20) NOT NULL,
Team2 varchar(20) NOT NULL,
Score int ,
D1_Player1 int NOT NULL,
D1_Player2 int NOT NULL,
D1_Player3 int NOT NULL,
D1_Player4 int NOT NULL,
D1_Player5 int NOT NULL,
D1_Player6 int NOT NULL,
D2_Player1 int NOT NULL,
D2_Player2 int NOT NULL,
D2_Player3 int NOT NULL,
D2_Player4 int NOT NULL,
D2_Player5 int NOT NULL,
D2_Player6 int NOT NULL,
CONSTRAINT Game_pk PRIMARY KEY (id)
);
CREATE TABLE Player (
Id int NOT NULL,
Name varchar(30) NOT NULL,
Surname varchar(30) NOT NULL,
Team_Name varchar(20) NOT NULL,
CONSTRAINT Player_pk PRIMARY KEY (id)
);
ALTER TABLE Player ADD CONSTRAINT DZ
FOREIGN KEY (Team_Name)
REFERENCES Team (Team_Name)
;
ALTER TABLE Game ADD CONSTRAINT MD
FOREIGN KEY (Team1, Team2)
REFERENCES Team (Team_Name, Team_Name)
;
ALTER TABLE Mecz ADD CONSTRAINT MZ
FOREIGN KEY (D1_Player1, D1_Player2, D1_Player3, D1_Player4, D1_zPlayer5, D1_Player6, D2_Player1, D2_Player2, D2_Player3, D2_Player4, D2_Player5, D2_Player6)
REFERENCES Player (id, id, id, id, id, id, id, id, id, id, id, id)
;
You should add one by one all foreign keys.
ALTER TABLE Game ADD CONSTRAINT MZ
FOREIGN KEY (D1_Player1)
REFERENCES Player (id)
;
ALTER TABLE Game ADD CONSTRAINT MZ2
FOREIGN KEY (D1_Player2)
REFERENCES Player (id)
;
ALTER TABLE Game ADD CONSTRAINT MZ3
FOREIGN KEY (D1_Player3)
REFERENCES Player (id)
;
GO
✓
dbfiddle here