SQL Queries/Subqueries - sql

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.

Related

Multiply columns and then sum rows: Oracle SQL

I'm trying to make a query in Oracle SQL Developer that must show the customer who has spend the biggest amount of money. So I have 4 tables: Cliente(Customer), Orden(Sale), Producto(Product) and a junction table to break many to many relationship between Orden and Producto.
CREATE TABLE Cliente(
id_cliente INT NOT NULL PRIMARY KEY,
Nombre VARCHAR(40) NOT NULL,
Apellido VARCHAR(40) NOT NULL,
Direccion VARCHAR(100) NOT NULL,
Telefono INT NOT NULL,
Tarjeta INT NOT NULL,
Edad INT NOT NULL,
Salario INT NOT NULL,
Genero VARCHAR(5) NOT NULL,
id_pais INT NOT NULL,
CONSTRAINT fk_cliente_pais FOREIGN KEY(id_pais) REFERENCES Pais(id_pais)
);
CREATE TABLE Producto(
id_producto INT NOT NULL PRIMARY KEY,
Nombre VARCHAR(40) NOT NULL,
Precio DECIMAL(10,2) NOT NULL,
id_categoria INT NOT NULL,
CONSTRAINT fk_categoria FOREIGN KEY(id_categoria) REFERENCES Categoria(id_categoria)
)
CREATE TABLE Orden(
id_orden INT NOT NULL,
linea_orden INT NOT NULL,
fecha_orden DATE NOT NULL,
id_cliente INT NOT NULL,
id_vendedor INT NOT NULL,
id_producto INT NOT NULL,
cantidad INT NOT NULL,
CONSTRAINT fk_orden_cliente FOREIGN KEY(id_cliente) REFERENCES Cliente(id_cliente),
CONSTRAINT fk_orden_vendedor FOREIGN KEY(id_vendedor) REFERENCES Vendedor(id_vendedor),
CONSTRAINT fk_orden_producto FOREIGN KEY(id_producto) REFERENCES Producto(id_producto),
CONSTRAINT pk_orden PRIMARY KEY(id_orden, linea_orden)
);
DROP TABLE Detalle;
CREATE TABLE Detalle(
id_detalle INT GENERATED ALWAYS AS IDENTITY,
id_producto INT NOT NULL,
id_orden INT NOT NULL,
linea_orden INT NOT NULL,
precio INT NOT NULL,
cantidad INT NOT NULL,
CONSTRAINT DETALLE_PRODUCTO
FOREIGN KEY (id_producto)
REFERENCES Producto (id_producto),
CONSTRAINT DETALLE_ORDEN
FOREIGN KEY (id_orden, linea_orden)
REFERENCES Orden (id_orden, linea_orden),
CONSTRAINT DETALLE_pk PRIMARY KEY(id_detalle, id_producto, id_orden)
);
On Table Detalle: precio (price), cantidad(quantity)
So I'm trying to get the Maximum total amount that a Customer has purchased by this query:
SELECT Cl.id_cliente, Cl.Nombre, Cl.Apellido,SUM( Detalle.precio * Detalle.cantidad) AS TOTAL
FROM Orden
INNER JOIN Cliente Cl ON Cl.id_cliente = Orden.id_cliente
INNER JOIN Detalle ON Detalle.id_orden = Orden.id_orden
GROUP BY Cl.id_cliente, Cl.Nombre, Cl.Apellido
ORDER BY TOTAL DESC;
But in the result, the TOTAL exceeds a lot from the right result, since I have another file with the result it should show.
I rewritten your query:
Select Cl.id_cliente, Cl.Nombre, Cl.Apellido,TOTAL
from(
SELECT Orden.id_cliente, SUM( Detalle.precio * Detalle.cantidad) AS TOTAL
FROM Detalle
JOIN Orden ON Detalle.id_orden = Orden.id_orden
GROUP BY Orden.id_cliente
) Orden
JOIN Cliente Cl ON Cl.id_cliente = Orden.id_cliente
ORDER BY TOTAL DESC
;
The data from details is summed multiple times, so calaculate them before joining
SELECT Cl.id_cliente, Cl.Nombre, Cl.Apellido,SUM(TOTAL ) AS TOTAL
FROM Orden
INNER JOIN Cliente Cl ON Cl.id_cliente = Orden.id_cliente
INNER JOIN (SELECT id_orden, SUM( Detalle.precio * Detalle.cantidad) AS TOTAL FROM Detalle GROUP BY id_orden) Detalle ON Detalle.id_orden = Orden.id_orden
GROUP BY Cl.id_cliente, Cl.Nombre, Cl.Apellido
ORDER BY TOTAL DESC;

Referencing the primary table in a sub-query

I have tables with some relations:
create table Students
(
[id] uniqueidentifier not null,
primary key (id),
[group] uniqueidentifier FOREIGN KEY REFERENCES [Groups]([id]) not null,
[name] nvarchar(20),
[surname] nvarchar(20)
)
create table Books
(
[id] uniqueidentifier not null,
primary key (id),
[name] nvarchar(100) not null,
[pages] int not null,
[author] uniqueidentifier FOREIGN KEY REFERENCES [Authors]([id])
)
create table StudentsCards
(
[id] uniqueidentifier not null,
primary key (id),
[student] uniqueidentifier FOREIGN KEY REFERENCES [Students]([id])
)
create table RelationsBooksToStudentsCards
(
[book] uniqueidentifier FOREIGN KEY REFERENCES [Books]([id]) not null,
[students_card] uniqueidentifier FOREIGN KEY REFERENCES [StudentsCards]([id]) not null
)
And I have query which trying to get sum of pages by students:
SELECT
[id] AS student_id, [name], [surname],
(SELECT SUM(b.pages)
FROM Students AS s
INNER JOIN RelationsBooksToStudentsCards AS r ON (SELECT [id] FRM StudentsCards WHERE student = s.id) = r.students_card
INNER JOIN Books AS b ON r.book = b.id
WHERE s.id LIKE student_id)
FROM
Students
Question: what do I need to do to use student_id in the query? Because now I got an exception:
Invalid column name 'student_id'
Ah, it was easy:
select [id], [name], [surname], (SELECT sum(b.pages)
FROM Students as s
inner JOIN RelationsBooksToStudentsCards as r
ON (select [id] from StudentsCards where student = s.id) = r.students_card
inner JOIN Books as b
ON r.book = b.id
where s.id like myAlias.id) from Students as myAlias

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

SQL Outer Join -- Join requires 3 tables

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.

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;