SQL Subqueries - Exists – Any - All - sql

I have a problem facing this subquery SQL exercice,using Northwind DB:
**16.
From order number 10251 show employee's name,company's name, order's
date,name of each product,quantity,unit price and
final price (= unitprice * quantity – unitprice*quantity*discount)
**
The following is my attempt of a solution, each of the subqueries work fine by their own,giving the expected result but it fails when combined together in the same query
select
(select FirstName from Employees where EmployeeID=Orders.EmployeeID)as 'Name',
(select Customers.CompanyName from Customers where Customers.CustomerID = Orders.CustomerID)'Company name' ,
(select Products.ProductName,Products.UnitPrice,
[Order Details].Quantity,
(Products.UnitPrice*[Order Details].Quantity-Products.UnitPrice*[Order Details].Quantity*[Order Details].Discount)
AS 'Final Price' from Products
INNER JOIN [Order Details] on Products.ProductID= [Order Details].ProductID
WHERE [Order Details].OrderID=10251),
Orders.OrderDate
from Orders
where OrderID=10251

I believe your query was failing because the third subquery (for Final Price) was returning a relation, as opposed to a scalar value.
I've re-written the query in a form that opts for joins rather than subqueries. Subqueries can be useful but I think using joins here makes the query little easier to read and work with.
select firstName as Name,
C.companyName as CompanyName,
P.UnitPrice * OD.Quantity
- (P.UnitPrice * OD.Quantity * OD.Discount)
as FinalPrice
from Orders as O
left join Employees as E
on E.employeeId = O.employeeId
left join Customers as C
on C.customerId = O.customerId
left join [Order Details] as OD
on OD.orderId = O.orderId
left join Products as P
on P.productId = OD.produtId

Related

I'm trying to use an aggregate function in order to consolidate the data but I'm not sure what I'm doing wrong

I have to find the total price per unit quantity and price. How can I make this work in a way where I can consolidate all the orders from one person with the total price that they ordered?
I'm new to SQL and not sure where to start to fix this.
SELECT DISTINCT Orders.OrderID, Customers.ContactName, Orders.OrderDate, [Order
Details].Quantity * [Order Details].UnitPrice
FROM Orders, Customers, [Order Details]
WHERE Orders.CustomerID = Customers.CustomerID
AND Orders.ShipCountry = 'Spain'
Three important things I can advice you to do:
Use explicit JOIN syntax: don't write your tables separately with comma, use explicit JOINs against them so it forces you to write their link at that moment and it's easier to read later. Your attempt was missing a link between the orders and the order details, probably making a lot of duplicates on your results.
Aggregates needs a GROUP BY. Whenever you want to apply aggregate functions like SUM, MAX, COUNT, you will (mostly) need a set of columns you want to group together. These columns go in the GROUP BY clause.
Don't use DISTINCT if you are unsure of the results you are getting. It seems that you used DISTINCT to cover up the missing link between orders and order details, so it just list uniques instead of the actual data your select is returning.
SELECT
C.CustomerID,
C.ContactName,
O.OrderID,
O.OrderDate,
TotalPrice = SUM(D.Quantity * D.UnitPrice)
FROM
Orders AS O
INNER JOIN Customers AS C ON O.CustomerID = C.CustomerID
INNER JOIN [Order Details] AS D ON O.OrderID = D.OrderID
WHERE
O.ShipCountry = 'Spain'
GROUP BY
C.CustomerID,
C.ContactName,
O.OrderID,
O.OrderDate
I think you want to do the join like this...
SELECT DISTINCT Orders.OrderID, Customers.ContactName, Orders.OrderDate,
[Order Details].Quantity * [Order Details].UnitPrice FROM Orders left join
Customers on Orders.CustomerID = Customers.CustomerID left join [Order
Details] on Orders.CustomerID = [Order Details].CustomerID where
Orders.ShipCountry = 'Spain'

Trying to sum part of the rows

So I have three tables
Orders:
CustomerID,OrderID
Order Details;
OrderID,ProductId,UnitPrice,Quantity,Discount
And Products:
ProductID,ProductName
And I need to combine these 2 tables and create this one:
[Orderd Details].CustomersID,Products.ProductName,FORMULA
Formula is how much money people spent money on this product. So I think I have to sum UnitPrice* Quantity*(1-Discount) from every order for this product.
Sadly I have no idea how should I do it. The best I did is:
SELECT o.CustomerID,p.ProductName,SUM(od.Quantity*od.UnitPrice*(1-od.Discount)) as 'SKZ'
FROM Customers as c, Orders as o,[Order Details] as od,Products as p
WHERE (o.OrderID=od.OrderID AND p.ProductID=od.ProductID)
GROUP BY od.ProductID ORDER BY o.CustomerID;
But it doesn't work.
First, learn explicit JOIN syntax. Simple rule: Never use commas in the FROM clause.
Second, you should include all non-aggregated columns in the GROUP BY:
SELECT o.CustomerID, p.ProductName,
SUM(od.Quantity * od.UnitPrice * (1 - od.Discount)) as SKZ
FROM Orders as o JOIN
[Order Details] od
ON o.OrderID = od.OrderID JOIN
Products p
ON p.ProductID = od.ProductID
GROUP BY o.CustomerID, p.ProductName
ORDER BY o.CustomerID;

Query returns cartesian product when not expected

Task: Select all orders having products belonging to ‘Sea Food’ category.
Result: OrderNo, OrderDate, Product Name
I write this query but it returns Cartesian products.
select o.orderid, o.orderdate as "Order Date", p.productname , ct.categoryname from orders o,
order_details od , products p , customers c ,categories ct
where
od.orderid = o.orderid and p.productid = od.productid and ct.categoryid = p.categoryid
and ct.categoryname = 'Seafood';
Question: What is wrong with my query ?
You're doing a CROSS JOIN on customers table since you forgot to specify the connection. This is why you should use explicit JOIN syntax rather than old syntax using commas in WHERE clause.
After translating your query into explicit syntax, you will see that there is no WHERE condition involving customers table:
select
o.orderid,
o.orderdate as "Order Date",
p.productname,
ct.categoryname
from
orders o,
inner join order_details od on od.orderid = o.orderid
inner join products p on p.productid = od.productid
inner join categories ct on ct.categoryid = p.categoryid
cross join customers c -- either you don't need this table, or you need to specify conditions
where
ct.categoryname = 'Seafood'
Basically the reason you got it was that your where clause omitted join condition involving customers table, so you were left with:
from (...), customers -- cross join when joining condition not applied in where clause

Link multiple table with math operation in SQL

I'm trying to find the revenue from customers in an country (United States).
The relevant tables are:
Order Details: Order ID, Unit price, quantity,
Orders: Order ID, customerID
Customers: customerID, country.
I'm not sure how to do this. I was thinking multiple inner join but it doesn't work.
The error message is "Syntax error (missing operator) in query expession 'ORDER DETAILS].ORDERID = ORDER.ORDERID
INNER JOIN CUSTOMERS ON CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID'
MS online said Error 3075
Here is what I have:
SELECT SUM(QUANTITY*UNITPRICE) AS Result
FROM [ORDER DETAILS]
INNER JOIN ORDERS ON [ORDER DETAILS].ORDERID = ORDER.ORDERID
INNER JOIN CUSTOMERS ON CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID
WHERE COUNTRY = 'Argentina'
Thanks in advance.
Edit: table structure
http://postimg.org/image/oojygytkv/
In Access if you are JOINing more than two tables together then it requires parenthesis. Try the following:
SELECT SUM(QUANTITY * UNITPRICE) AS Result
FROM ([ORDER DETAILS]
INNER JOIN ORDERS ON [ORDER DETAILS].ORDERID = ORDERS.ORDERID)
INNER JOIN CUSTOMERS ON CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID
WHERE COUNTRY = 'Argentina'

SQL Server query for total dollar amount of orders per customerID

I have two tables that I need to create a query for. I'm sure I'll need to join them as well.
I need to take the CustomerName and Address of customer from my Customer table but I also need the query to show the total dollar amount of all the orders placed by customer. So if the customer spent for example $300 dollars this year in total, that $300 is the output I'm trying to achieve.
I have a table called Order Details that uses an OrderID which is tied to a CustomerID and there are unitprice and quantity columns in the Order Details table. I'm trying to figure out how to multiple these but I am going crazy.
I have tried this to get at least the total from the orders but I have syntax errors for sure:
SELECT unitprice,
quantity
FROM [Order details] (unitprice * quantity) AS Totalorders,
from [Order Details]
WHERE orderid > 0
also this without any luck :
SELECT customers.companyname AS 'Company Name',
customers.address AS 'Address',
[order details].unitprice * [order details].quantity AS 'Orders'
FROM customers
LEFT JOIN orders
ON customers.customerid = orders.customerid
ORDER BY customers.companyname,
customers.address,
orders
Thanks
You need to join in the order details and do a group by aggregation:
SELECT c.CompanyName AS "Company Name",
c.Address AS "Address",
sum(od.Unitprice * od.quantity) as "Orders"
FROM Customers c LEFT JOIN
Orders o
ON c.CustomerID = o.CustomerID left join
[Order Details] od
on od.orderid = o.orderid
GROUP BY c.CompanyName, c.Address
ORDER BY c.CompanyName, c.Address
In addition, I made some stylistic changes. I added aliases to the table names. I find it much easier to read c.CompanyName rather than Customers.CompanyName. I changed the delimiter on the column aliases to use double quotes rather than single quotes. I associate single quotes with string constants inside the statement.
if it s one-to-many relationship, your query will look something like:
SELECT
Customers.CompanyName AS 'Company Name',
Customers.Address AS 'Address',
SUM(O.Unitprice * O.quantity) as 'Orders'
FROM Customers
LEFT JOIN [Order Details] O
ON Customers.CustomerID = O.CustomerID
GROUP BY Customers.CompanyName, Customers.Address
ORDER BY Customers.CompanyName, Customers.Address