SQL Outer Join -- Join requires 3 tables - sql

I'm using SQL Server query designer to try and form an outer query that will return the full name and address of each insured with home policies and those without policies. My create statements are the following:
CREATE TABLE Address (
AddressID integer NOT NULL,
HouseNumber Integer NOT NULL,
Street varchar(20) NOT NULL,
CityCounty varchar(20) NOT NULL,
StateAbb char(2),
CountryAbb char(2) NOT NULL,
Zip char(5) NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Address PRIMARY KEY (AddressID));
CREATE TABLE Insured(
InsuredID integer NOT NULL,
FirstName varchar(15) NOT NULL,
LastName varchar(15) NOT NULL,
MI char(1),
DateOfBirth date NOT NULL,
CreditScore integer NOT NULL,
AddressID integer NOT NULL,
DriversLicenseNumber varchar(35),
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Insured PRIMARY KEY (InsuredID),
CONSTRAINT FK_InsuredAddress FOREIGN KEY (AddressID) references Address);
CREATE TABLE Policy(
PolicyID integer NOT NULL,
EffectiveDate date NOT NULL,
TerminationDate date NOT NULL,
Amount Numeric (8,2) NOT NULL,
PolicyYear integer NOT NULL,
PolicyType char(1) NOT NULL,
InsuredID integer NOT NULL,
AddressID integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Policy PRIMARY KEY (PolicyID),
CONSTRAINT FK_PolicyAddress FOREIGN KEY (AddressID) references Address,
CONSTRAINT FK_PolicyInsured FOREIGN KEY (InsuredID) references Insured);
CREATE TABLE Home(
PolicyID integer NOT NULL,
ExteriorType varchar(30) NOT NULL,
Alarm char(3) NOT NULL,
DistanceToFireStation integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Home PRIMARY KEY (PolicyID),
CONSTRAINT FK_HomePolicy FOREIGN KEY (PolicyID) references Policy);
CREATE TABLE Auto(
PolicyID integer NOT NULL,
VinNumber varchar(30) NOT NULL,
Make varchar(15) NOT NULL,
Model varchar(20) NOT NULL,
MilesPerYear integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Auto PRIMARY KEY (PolicyID),
CONSTRAINT FK_AutoPolicy FOREIGN KEY (PolicyID) references Policy);
I believe that the query requires tables address, insured, policy and an outer right or left join but I cant get SQL server to recognize this as it keeps forming an inner join and cross join. What do I need for a query that returns insureds with home policies and their addresses and insureds with no policy and their addresses?
What I've tried so far:
SELECT Insured.InsuredID, Insured.FirstName,
Insured.LastName, Address.HouseNumber,
Policy.PolicyID
FROM Address RIGHT JOIN Policy
ON Address.AddressID = Policy.AddressID
RIGHT JOIN Insured ON Policy.AddressID = Insured.AddressID
ORDER BY Insured.InsuredID
This is the most recent query that returns what I need for insureds with a home policy but for the insureds without a policy I get nulls in the address.
SELECT i.InsuredID, i.FirstName, i.MI, i.LastName,
a.HouseNumber, a.Street, a.CityCounty, a.StateAbb, a.CountryAbb, a.Zip
FROM INSURED i
LEFT JOIN (SELECT * FROM Policy WHERE PolicyType = 'H') HomePolicy on
i.InsuredID = HomePolicy.InsuredID
LEFT JOIN Address a on HomePolicy.AddressID = a.AddressID;

Could you try this query:
SELECT i.InsuredID,
i.FirstName,
i.LastName,
a.HouseNumber,
p.PolicyID
FROM insured i
LEFT JOIN policy p ON i.AddressID = p.AddressID AND p.PolicyType = 'H'
LEFT JOIN address a ON i.AddressID = a.AddressID
ORDER BY i.InsuredID;
I think the joins were in the wrong order. Does this give you what you need?
Update: Joining the Insured table to the Address table will show you addresses regardless of if they have a policy or not.

Database design seem good.I think we have minor doubts regarding "PolicyType" column. what value it hold and what is the purpose of this column.
Say PolicyType='H' it mean that it is home policy . Or other way of finding same query is to check if that policyid exists in home table.
Is this correct ?
Main query,
What do I need for a query that returns insureds with home policies
and their addresses and insureds with no policy and their addresses?
Check this script,
--insureds with home policies and their addresses
select i.InsuredID,
i.FirstName,
i.LastName
A.HouseNumber
,1 INDICATE
from Insured i
INNER JOIN policy p ON i.InsuredID = p.InsuredID
INNER JOIN [Address] A ON A.ADDRESSID=I.ADDRESSID
WHERE EXISTS(SELECT PolicyID FROM Home H WHERE h.PolicyID=P.PolicyID)
AND NOT EXISTS(SELECT PolicyID FROM [Auto] a WHERE A.PolicyID=P.PolicyID)
UNION ALL
--insureds with no policy and their addresses
select i.InsuredID,
i.FirstName,
i.LastName
,A.HouseNumber
,0 INDICATE
from Insured i
INNER JOIN [Address] A ON A.ADDRESSID=I.ADDRESSID
WHERE EXISTS(SELECT InsuredID FROM policy p WHERE i.InsuredID = p.InsuredID )
I have use "EXISTS clause" because that table column is not require in your output.

Related

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

Ambiguous column name 'ProductNumber'

Can't figure out why my question 3 is getting the error mentioned above.
Below is my code
/* Question 1 */
CREATE TABLE CUSTOMERS
(
CustomerID INT PRIMARY KEY,
CustFirstName VARCHAR(50) NOT NULL,
CustLastName VARCHAR(50) NOT NULL,
CustStreetAddress VARCHAR(50) NOT NULL,
CustCity VARCHAR(50) NOT NULL,
CustState VARCHAR(26) NOT NULL,
CustZipCode INT NOT NULL,
CustAreaCode INT NOT NULL,
CustPhoneNumber VARCHAR (26) NOT NULL
);
CREATE TABLE EMPLOYEES
(
EmployeeID INT PRIMARY KEY,
EmpFirstName VARCHAR(50) NOT NULL,
EmpLastName VARCHAR(50) NOT NULL,
EmpCity VARCHAR (50) NOT NULL,
EmpState VARCHAR(26) NOT NULL,
EmpZipCode INT NOT NULL,
EmpAreaCode INT NOT NULL,
EmpPhoneNumber VARCHAR(26) NOT NULL,
EmpBirthDate DATE NOT NULL
);
CREATE TABLE ORDERS
(
OrderNumber INT PRIMARY KEY,
OrderDate DATE NOT NULL,
ShipDate DATE NOT NULL,
CustomerID INT NOT NULL,
EmployeeID INT NOT NULL,
FOREIGN KEY(EmployeeID) REFERENCES EMPLOYEES(EmployeeID),
FOREIGN KEY(CustomerID) REFERENCES CUSTOMERS(CustomerID)
);
CREATE TABLE CATEGORIES
(
CategoryID INT PRIMARY KEY,
CategoryDescription VARCHAR(255) NOT NULL
);
CREATE TABLE PRODUCTS
(
ProductNumber INT PRIMARY KEY,
ProductName VARCHAR(50) NOT NULL,
ProductDescription VARCHAR(255) NOT NULL,
RetailPrice INT NOT NULL,
QuantityOnHand INT NOT NULL,
CategoryID INT NOT NULL,
FOREIGN KEY(CategoryID) REFERENCES CATEGORIES (CategoryID)
);
CREATE TABLE ORDER_DETAILS
(
OrderNumber INT NOT NULL,
ProductNumber INT NOT NULL,
QuotedPrice INT NOT NULL,
QuantityOrdered INT NOT NULL,
PRIMARY KEY (OrderNumber, ProductNumber),
FOREIGN KEY (OrderNumber) REFERENCES ORDERS(OrderNumber),
FOREIGN KEY(ProductNumber) REFERENCES PRODUCTS(ProductNumber)
);
CREATE TABLE VENDORS
(
VendorID INT PRIMARY KEY,
VendName VARCHAR(100) NOT NULL,
VendStreetAddress VARCHAR(50) NOT NULL,
VendCity VARCHAR(50) NOT NULL,
VendState VARCHAR(26) NOT NULL,
VendFaxNumber VARCHAR(50) NOT NULL,
VendWebPage VARCHAR(100) NOT NULL,
VendEmailAddress VARCHAR(100) NOT NULL
);
CREATE TABLE PRODUCT_VENDORS
(
ProductNumber INT NOT NULL,
VendorID INT NOT NULL,
WholeSalePrice INT NOT NULL,
DaysToDeliver INT NOT NULL,
PRIMARY KEY(ProductNumber, VendorID),
FOREIGN KEY(ProductNumber) REFERENCES PRODUCTS(ProductNumber),
FOREIGN KEY(VendorID) REFERENCES Vendors(VendorID)
);
/* QUESTION 2 */
SELECT
OrderDate, CustFirstName, CustLastName
FROM
CUSTOMERS C, ORDERS O
WHERE
C.CustomerID = O.OrderNumber;
/* QUESTION 3 */
SELECT
ProductNumber, WholeSalePrice, VendName
FROM
PRODUCTS P, PRODUCT_VENDORS PV, VENDORS V
WHERE
P.PRODUCTNUMBER = PV.ProductNumber AND PV.VendorID = V.VendorID;
I got the error
Ambiguous column name 'ProductNumber'
Because there are two table have column name of ProductNumber in your query you need to tell DB engine which column you want to get.
Also, use JOIN instead of , comma CROSS JOIN, because Join is more clear than a comma on the relationship between the two tables
SELECT PV.ProductNumber, WholeSalePrice, VendName
FROM PRODUCTS P
JOIN PRODUCT_VENDORS PV ON P.PRODUCTNUMBER = PV.ProductNumber
JOIN VENDORS V ON PV.VendorID = V.VendorID;
Your query stipulates SELECT ProductNumber From two tables that both have ProductNumber. In the SELECT columns list, prefix ProductNumber with the table name from which you want to receive the data.
also, Have a look at your question 2. I don't think you really want to join customer id to order number, and you should use JOIN syntax intead of joining in the WHERE clause
Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it. See, with your query, you're just literally calling the ProductNumber field in which the SQL has no idea where to get it since there are ProductNumber fields on both Tables, and you didn't specify any table.
so it is better when you have same column in multiple tables use table preface 1st then column like table1.col1,table2.col2
so in your case
SELECT p.ProductNumber, WholeSalePrice, v.VendName
FROM PRODUCTS P join
PRODUCT_VENDORS PV on P.PRODUCTNUMBER = PV.ProductNumber //
join VENDORS V on PV.VendorID = V.VendorID //use join instead your's

How to select all relations that current user is involved in ? ASP.NET SQL Server

I have this database with users and relations. I simply want to show username, firstName and lastName of all the relations that some specific (current logged in user) userID is present in. How do I do this?
This is my best try.
SELECT
UserRelationship.relationshipType,
UserRelationship.userFirstID, UserRelationship.userSecondID,
[User].username, [User].firstName, [User].lastName
FROM
[User]
INNER JOIN
UserRelationship ON [User].userID = UserRelationship.userFirstID
AND UserRelationship.relationshipType = 'friends'
OR [User].userID = UserRelationship.userSecondID
AND UserRelationship.relationshipType = 'friends'
WHERE
([User].userID = #userID)
This returns all relations, but the username, firstname and lastname of current user.
These are my tables:
CREATE TABLE [dbo].[UserRelationship]
(
[userFirstID] INT NOT NULL,
[userSecondID] INT NOT NULL,
[initiatedBy] NVARCHAR (50) NOT NULL,
[relationshipType] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_UserRelationship]
PRIMARY KEY CLUSTERED ([userFirstID] ASC, [userSecondID] ASC),
CONSTRAINT [FK_UserRelationship_userFirstID]
FOREIGN KEY ([userFirstID]) REFERENCES [dbo].[User] ([userID]),
CONSTRAINT [FK_UserRelationship_initiatedBy]
FOREIGN KEY ([initiatedBy]) REFERENCES [dbo].[User] ([username]),
CONSTRAINT [CK_UserRelationship_relationshipType]
CHECK ([relationshipType]='pending' OR [relationshipType]='friends')
);
and
CREATE TABLE [dbo].[User]
(
[userID] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (50) NOT NULL,
[firstName] NVARCHAR (50) NULL,
[lastName] NVARCHAR (50) NULL,
[dateOfBirth] DATE NULL,
[city] NVARCHAR (50) NULL,
[address] NVARCHAR (50) NULL,
[phoneNumber] INT NULL,
[email] NVARCHAR (50) NULL,
[rank] NVARCHAR (50) NULL,
[profilImage] NVARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([userID] ASC),
CONSTRAINT [AK_User_username]
UNIQUE NONCLUSTERED ([username] ASC)
);
In my UserRelationship table, I store all relations by always making sure userFirstID is lower than userSecondID. So I only have 1 record per relation.
Do you want to get the names of the users the current user has a friendship with? Then one possibility is to join the user's table again twice for each the first and the second id in the relationship's table and check in a CASE ... END which one is the other user and return their name.
SELECT UserRelationship.relationshipType,
UserRelationship.userFirstID,
UserRelationship.userSecondID,
[User].username,
[User].firstName,
[User].lastName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.userName
WHEN OtherUser2.userId
THEN OtherUser1.userName
END OtherUserUserName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.firstName
WHEN OtherUser2.userId
THEN OtherUser1.firstName
END OtherUserFirstName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.lastName
WHEN OtherUser2.userId
THEN OtherUser1.lastName
END OtherUserLastName
FROM [User]
INNER JOIN UserRelationship
ON [User].userID IN (UserRelationship.userFirstID,
UserRelationship.userSecondID)
AND UserRelationship.relationshipType = 'friends'
INNER JOIN [User] OtherUser1
ON OtherUser1.userID = UserRelationship.userFirstID
INNER JOIN [User] OtherUser2
ON OtherUser2.userID = UserRelationship.userSecondID
WHERE ([User].userID = #userID);
(Assuming a user cannot be a friend of themselves. That would require an extension of the CASE .... ENDs for the case of all three ids being equal.)

SQL Queries/Subqueries

I was wondering if someone could help me with this query? I am very stuck on this one:
"Show the sum of HoursWorked for each Type of OWNER but exclude services of employees who have ExperienceLevel of Junior and exclude any Type with less than three members."
CREATE TABLE OWNER
(
OwnerID Int NOT NULL IDENTITY (1,1) PRIMARY KEY,
OwnerName Char(30) NOT NULL,
OwnerEmail VarChar(100) NULL,
OwnerType Char(15) NOT NULL,
);
CREATE TABLE PROPERTY
(
PropertyID Int NOT NULL IDENTITY(1,1) PRIMARY KEY,
PropertyName Char(30) NOT NULL,
Street Char(20) NOT NULL,
City Char(25) NOT NULL,
State Char(10) NOT NULL,
Zip Char(5) NOT NULL,
OwnerID Int NOT NULL,
CONSTRAINT PROP_OWN_FK FOREIGN KEY(OwnerID)
REFERENCES OWNER(OwnerID),
);
CREATE TABLE GG_EMPLOYEE
(
EmployeeID Int NOT NULL IDENTITY(1,1) PRIMARY KEY,
LastName Char(35) NOT NULL,
FirstName Char(35) NOT NULL,
CellPhone Char(20) NOT NULL,
ExperienceLevel Char(25) NOT NULL,
);
CREATE TABLE SERVICE
(
PropertyID Int NOT NULL,
EmployeeID Int NOT NULL,
ServiceDate Char(15) NOT NULL,
HoursWorked Char(5) NOT NULL,
CONSTRAINT SERVICE_PK PRIMARY KEY(PropertyID, EmployeeID, ServiceDate),
CONSTRAINT SER_PRO_FK FOREIGN KEY(PropertyID)
REFERENCES PROPERTY(PropertyID),
CONSTRAINT SER_GG_EMP_FK FOREIGN KEY(EmployeeID)
REFERENCES GG_EMPLOYEE(EmployeeID),
);
SELECT o.OwnerType, SUM(Cast(HoursWorked as INT)) Sum_HrsWorked
FROM SERVICE s
INNER JOIN GG_EMPLOYEE e
ON s.EmployeeId = e.EmployeeId
INNER JOIN PROPERTY p
ON s.PropertyId = p.PropertyId
INNER JOIN OWNER o
ON o.OwnerID = p.OwnerID
WHERE e.ExperienceLevel <> 'JUNIOR'
Group By o.OwnerType
HAVING COUNT(OwnerType) > 3
Select Tbl1.OwnerName,Sum(TBl2.TTLHoursWorked) as TTLHoursWorked
From
(
Select TBl1.OwnerID,Tbl1.OwnerName,Tbl2.PropertyID,Tbl2.PropertyName
From Owner Tbl1
Inner Join
PROPERTY Tbl2
On Tbl1.OwnerID=Tbl2.OwnerID
)Tbl1
Inner Join
(
Select Tbl2.PropertyID,Cast(HoursWorked as numeric(5,4)) as TTLHoursWorked
From (Select * From GG_EMPLOYEE Where ExperienceLevel in(Select ExperienceLevel
From GG_EMPLOYEE
Where ExperienceLevel<>'Junior'
Group by ExperienceLevel Having Count(*)>3))as Tbl1
Inner Join SERVICE as Tbl2
On Tbl1.EmployeeID=Tbl2.EmployeeID
)Tbl2
On Tbl1.PropertyID=Tbl2.PropertyID
Group by Tbl1.OwnerName
SELECT o.OwnerType, SUM(CAST(s.HoursWorked as INT))
FROM
owner o
INNER JOIN property p
On o.ownerid = p.ownerid
INNER JOIN service s
ON p.propertyid = s.propertyid
INNER JOIN GG_employee e
On s.employeeid = e.employeeid
And e.experiencelevel <> 'junior'
GROUP BY
O.ownertype
HAVING
COUNT(DISTINCT o.ownerid) >= 3
Please forgive typos and capitalization as I'm on my phone.

Restricting values in a table used in a FULL OUTER JOIN

This concerns Oracle SQL.
Considering the following 3 tables:
TRIP_SEGMENT:
CREATE TABLE TRIP_SEGMENT(
SEG_ID NUMBER(6) NOT NULL,
DIRECTION VARCHAR(8) NOT NULL,
DEPARTURE_LOCATION VARCHAR(50) NOT NULL,
DESTINATION VARCHAR(50) NOT NULL,
SEGMENT_PRICE NUMBER(5,2) NULL,
TRIP_ID NUMBER(6) NOT NULL,
CONSTRAINT chk_SEG_DIRECTION CHECK (DIRECTION IN ('Outbound','Inbound')),
CONSTRAINT pk_SEGMENT PRIMARY KEY (SEG_ID),
CONSTRAINT fk_TRIP_ID FOREIGN KEY (TRIP_ID) REFERENCES TRIP(TRIP_ID)
);
TRANSPORTATION:
CREATE TABLE TRANSPORTATION(
TRANSP_BOOK_ID NUMBER(6) NOT NULL,
TRANSP_PRICE NUMBER(5,2) NULL,
DEPARTURE_DATE DATE NULL,
ARRIVAL_DATE DATE NULL,
EXT_BOOK_ID NUMBER(6) NULL,
SEG_ID NUMBER(6) NOT NULL,
SERV_TYPE_ID NUMBER(3) NOT NULL,
PARTNER_ID NUMBER(3) NULL,
CONSTRAINT pk_TRANSP_BOOK_ID PRIMARY KEY (TRANSP_BOOK_ID),
CONSTRAINT fk_TRANSP_SEG_ID FOREIGN KEY (SEG_ID) REFERENCES TRIP_SEGMENT(SEG_ID),
CONSTRAINT fk_TRANSP_SERV_ID FOREIGN KEY (SERV_TYPE_ID) REFERENCES SERVICE_TYPE(SERV_TYPE_ID),
CONSTRAINT fk_TRANSP_PARTNER_ID FOREIGN KEY (PARTNER_ID) REFERENCES PARTNER(PARTNER_ID)
);
PARTNER:
CREATE TABLE PARTNER(
PARTNER_ID NUMBER(3) NOT NULL,
PARTNER_NAME VARCHAR(50) NOT NULL,
CONTACT_FNAME VARCHAR(20) NOT NULL,
CONTACT_LNAME VARCHAR(20) NOT NULL,
ADDRESS VARCHAR(100) NULL,
PHONE_NO NUMBER(20) NOT NULL,
EMAIL VARCHAR(50) NULL,
SERV_TYPE_ID NUMBER(3) NOT NULL,
CONSTRAINT pk_PARTNER_ID PRIMARY KEY (PARTNER_ID),
CONSTRAINT fk_PART_SERV_ID FOREIGN KEY (SERV_TYPE_ID) REFERENCES SERVICE_TYPE(SERV_TYPE_ID)
);
I wanted to create a FULL OUTER JOIN like this:
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN PARTNER P
ON T.PARTNER_ID = P.PARTNER_ID;
...but have it restricted to PARTNER.PARTNER_ID < 6. If I just add a WHERE clause at the end of the JOIN, this will restrict all the values to those where there is an association with PARTNER.PARTNER_ID < 6, therefore defeating the purpose of the FULL OUTER JOIN.
So far, I've come up with this solution:
First, create a table that only contains PARTNER.PARTNER_ID < 6 :
CREATE TABLE TRANSPORTATION_PARTNER AS SELECT * FROM PARTNER WHERE PARTNER_ID < 6;
Then, use that table in the FULL OUTER JOIN instead:
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, TP.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN TRANSPORTATION_PARTNER TP
ON T.PARTNER_ID = TP.PARTNER_ID;
This works fine and it demonstrates what I'm trying to achieve, however I was wondering if there is a way of doing in one single query AND using a subquery.
Thank you!
YES, just do something like :
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
FULL OUTER JOIN (SELECT *
FROM PARTNER
WHERE PARTNER.PARTNER_ID < 6) P
ON T.PARTNER_ID = P.PARTNER_ID;
You are placing restrictions on the rows to be selected so you can use LEFT JOIN instead of the FULL OUTER JOIN. Try something like
SELECT TS.SEG_ID, TS.DEPARTURE_LOCATION, TS.DESTINATION, P.PARTNER_NAME
FROM TRIP_SEGMENT TS
FULL OUTER JOIN TRANSPORTATION T
ON TS.SEG_ID = T.SEG_ID
LEFT OUTER JOIN PARTNER P
ON T.PARTNER_ID = P.PARTNER_ID AND P.Partner_ID = 6;