Ambiguous column name 'ProductNumber' - sql

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

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;

Direct relation in SQL

I'm a beginner in SQL and I'm trying to make a small database, but I was asked to make a direct relation between OrderNumber in Orders table and CustomerNumber in Customers table, aren't I using a direct relation in here?.
Here is my code:
Customers table:
CREATE TABLE Customers
(
CustomerNumber VARCHAR(25) PRIMARY KEY NOT NULL,
CustomerName VARCHAR(50),
Phone INT NOT NULL,
Country VARCHAR(50),
City VARCHAR(50),
State VARCHAR(50),
PostalCode VARCHAR(5) NOT NULL
);
Orders table:
CREATE TABLE Orders
(
OrderNumber VARCHAR(25) ,
CustomerNumber VARCHAR(25) PRIMARY KEY NOT NULL,
ProductName VARCHAR(200) NOT NULL UNIQUE,
OrderDate DATE NOT NULL,
requiredDate DATE NOT NULL,
Status VARCHAR(50)
);
I believe, you probably want something like this:
CREATE TABLE Customers
(
CustomerNumber INT PRIMARY KEY NOT NULL,
CustomerName VARCHAR(50),
Phone INT NOT NULL,
Country VARCHAR(50),
City VARCHAR(50),
State VARCHAR(50),
PostalCode VARCHAR(5) NOT NULL
);
CREATE TABLE Orders
(
OrderNumber INT PRIMARY KEY NOT NULL,
CustomerNumber INT NOT NULL FOREIGN KEY REFERENCES Customers(CustomerNumber),
ProductName VARCHAR(200) NOT NULL UNIQUE,
OrderDate DATE NOT NULL,
requiredDate DATE NOT NULL,
Status VARCHAR(50)
);
Changed the datatype of CustomerNumber and OrderNumber to INT
Made Orders.CustomerNumber a foreign key with a relation to the Customer table (CustomerNumber column)

How to Relate 2 table with each other with 2 foreign keys

Here is my code it generates Foreign key conflict error
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NOT NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NOT NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
You cannot do that. This is a circular reference.
This is a bad design but if you want to do that, you need to make foreign key columns Nullable.
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
Then you need to update reference fields after inserting records in tblBatches and tblProducts.
The good design says you need to create a bridge table like this:
CREATE TABLE tblProductsBatch
(
ID int NOT NULL IDENTITY PRIMARY KEY,
ProductID int NOT NULL,
BatchID int NOT NULL
)
And after inserting product and batch, you need to insert a record in this table to link rows to each other.

Error relate SQL Server tables

I have the following problem: when we run the code, it displays the following error:
There are primary keys or candidates in the reference Ticket table
that match the list of referencing columns in foreign key '
FK__Payment__PkTicke__1A14E395
Code:
create table SystemUser
(
PkUser int identity(1,1),
UserLogin nvarchar(20) not null unique,
UserPassword nvarchar(50) not null,
UserName nvarchar(50) not null,
UserCpf nvarchar(50) not null,
UserBirth datetime not null,
UserGender nvarchar(15) not null,
AddressCep int not null,
AddressStreet nvarchar(50) not null,
AddressNumber nvarchar(20) not null,
AddressComplement nvarchar(50) not null,
AddressCity nvarchar(50) not null,
AddressState nvarchar(50) not null,
primary key(PkUser)
)
create table Attractions
(
PkAttraction integer identity(1,1) ,
AttractionName nvarchar(50) not null unique,
AttractionDate datetime not null,
AttractionDescription nvarchar(150) not null
primary key(PkAttraction)
)
create table Ticket
(
PkTicket int identity(1,1),
PkUser int not null,
PkAttraction int not null,
TicketPrice decimal not null,
primary key(PkTicket, PkUser, PkAttraction),
foreign key(PkUser) references SystemUser(PkUser),
foreign key(PkAttraction) references Attractions(PkAttraction)
)
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
foreign key(PkTicket) references Ticket(PkTicket),
)
create table FormPayment
(
PkFromPayment int identity(1,1),
PkPayment int not null,
ShareValue decimal not null,
ExpirationDate datetime not null
primary key(PkFromPayment, PkPayment),
foreign key(PkPayment) references Payment(PkPayment),
)
Your Ticket table as a primary key made up from 3 columns:
create table Ticket
(
.....
primary key(PkTicket, PkUser, PkAttraction),
....
)
Any table that wants to reference that table Ticket must also provide all 3 columns for the foreign key.
You cannot reference only part of a primary key - if you want to reference it, you must have all columns that it contains - otherwise you cannot establish a FK relationship.
So you must add the PkUser and PkAttraction columns to your Payment table so that you can establish this FK relationship:
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
PkUser int not null, // add this
PkAttraction int not null, // add this
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
// change to this
foreign key(PkTicket, PkUser, PkAttraction) references Ticket(PkTicket, PkUser, PkAttraction)
.....
)
When you not specify a name for FK and PK, SQL server generates a name. in this case, looks like SQL server generates duplicate name.
If you specify name for FK and PK, it will work.

Where clause in Mutiple table sql joins

TABLES
CREATE TABLE LocalBusiness
(
BusinessID INT NOT NULL PRIMARY KEY,
BusinessName VARCHAR2 (20) NOT NULL,
TypeID INT,
Latitude DECIMAL (10,2),
Longitude DECIMAL (10,2),
Web_address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
official_rating int,
min_price NUMBER(4,2),
max_price NUMBER(4,2),
FOREIGN KEY (TypeID) REFERENCES LocalBusinessType (TypeID),
CONSTRAINT chk_Officialrating CHECK (official_rating> 0 AND official_rating<6 )
);
CREATE TABLE Address
(
AddressID INT NOT NULL PRIMARY KEY,
BusinessID INT,
AreaID INT,
Address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
FOREIGN KEY (AreaID) REFERENCES Area (AreaID)
);
CREATE TABLE Phone
(
PhoneNoID INT NOT NULL PRIMARY KEY,
PhoneNo VARCHAR2 (15) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT PhoneNo_unique UNIQUE (PhoneNo)
);
CREATE TABLE Email
(
EmailID INT NOT NULL PRIMARY KEY,
email_address VARCHAR2 (50) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT email_unique UNIQUE (email_address)
);
CREATE TABLE Area
(
AreaID INT NOT NULL PRIMARY KEY,
AreaName VARCHAR2 (20) NOT NULL,
Region VARCHAR2 (20) NOT NULL
);
SELECT statement:
SELECT
LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price,
Phone.description, Phone.PhoneNo,
Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM
LocalBusiness
JOIN
Address ON LocalBusiness.BusinessID = Address.BusinessID
JOIN
Area ON Address.AreaID = Area.AreaID
AND LocalBusiness.BusinessID = Address.BusinessID
JOIN
Phone ON Phone.BusinessID = LocalBusiness.BusinessID
JOIN
Email ON Email.BusinessID = LocalBusiness.BusinessID
WHERE
TypeID = '1'
ORDER BY
LocalBusiness.BusinessName ASC;
The where clause in the sql join statement written above seem to be ineffective as the some values for the TypeID return incomplete data while others return no rows at all. How do I go about fixing this?
Yyou repeat a condition
AND LocalBusiness.BusinessID=Address.BusinessID in JOIN Area
Try avoinding this repetition
SELECT LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price, Phone.description,
Phone.PhoneNo, Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM LocalBusiness
JOIN Address ON LocalBusiness.BusinessID=Address.BusinessID
JOIN Area ON Address.AreaID=Area.AreaID
JOIN Phone ON Phone.BusinessID=LocalBusiness.BusinessID
JOIN Email ON Email.BusinessID=LocalBusiness.BusinessID
WHERE TypeID = '1'
ORDER BY LocalBusiness.BusinessName ASC;
Otherwise check th consistence of your data ..