Link multiple table with math operation in SQL - 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'

Related

SQL Subqueries - Exists – Any - All

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

SQL - cannot perform distinct count when joining two tables

I have two tables: Customers and Orders. I do a left join of Customers and Orders on CustomerID column which is primary key in Customers and foreign key in Orders.
When I list CustomerID after joining, I get the list as expected.
When I count the number of CustomerID, again I get the number of record I am expecting.
When I use distinct count for CustomerID, i get an error.
1.
select Customers.CustomerID as list
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
2.
select count(Customers.CustomerID) as numRecord
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
3.
select count(distinct (Customers.CustomerID)) as numRecord
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
I cannot understand where is the error. Any help would be appreciated.
The error:
Error in SQL:
Syntax error (missing operator) in query expression 'count(distinct Customers.CustomerID)'.
You don't need the () around Customers.CustomerID in count(distinct ..)
select count(distinct Customers.CustomerID) as numRecord
from Customers
left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;

SQL: How to select two input parameters from three tables?

Okay, this is related to database given on http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
I need to find list of Customers,OrderID, ProductID for orders from Spain.
The table 'Orders' has OrderID and table 'Products' consists of ProductID whereas the table 'OrderDetails' consists of OrderID and ProductID. I use the following code but I get an error message 'Error: 1 ambiguous column: OrderID'
Here is my code
SELECT CustomerName, Country, OrderID, ProductID
FROM Customers, Orders, Products, OrderDetails
WHERE Customers.CustomerID = Orders.CustomerID
AND Orders.OrderID = OrderDetails.OrderID
AND Products.ProductID = OrderDetails.ProductID AND Country = 'Spain'
Can someone correct any mistake?
You need to use the alias names like this:
SELECT Customers.CustomerName,
Customers.Country, --Specify the correct table in which you have Country column
Orders.OrderID,
Products.ProductID
FROM Customers
inner join Orders ON Customers.CustomerID = Orders.CustomerID
inner join OrderDetails on Orders.OrderID = OrderDetails.OrderID
inner join Products on Products.ProductID = OrderDetails.ProductID
where Customers.Country = 'Spain'
Also try to avoid comma seperated JOINS. A good read: Bad habits to kick : using old-style JOINs

Using DISTINCT in SQL Query

How do i use DISTINCT command in a SQL query to show the supplier id, company name, and the number of distinct products from that supplier that were ordered prior to a specific date? I ran the code in Access but it doesn't translate over to SQL efficiently. The table appears.
[Supplier ID Company Name Product Name Order Date
1 Exotic Liquids Chang 17-Aug-94
1 Exotic Liquids Chang 22-Nov-94
1 Exotic Liquids Aniseed Syrup 26-Sep-94]
The code I have so far is the following. Where I get confused is where to put the DISTINCT statement. Should it be immediately after the Select? Should it go in Parentheses in addition to the SELECT? Excuse my lack of knowledge on this subject in advance.
SELECT Suppliers.SupplierID, Customers.CompanyName, Products.ProductName,
Orders.OrderDate
FROM Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate <='1/1/1999'
ORDER BY Suppliers.SupplierID
You can either distinct by all columns selected :
SELECT DISTINCT
Suppliers.SupplierID, Customers.CompanyName, Products.ProductName,
Orders.OrderDate
FROM
Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE
Orders.OrderDate <='1/1/1999'
ORDER BY
Suppliers.SupplierID
or use group by instead if you need to distinct only by SupplierID. DISTINCT is not a function, hence DISTINCT(Suppliers.SupplierID) means the same as simply put DISTINCT word after SELECT in this case (see the 2nd reference below).
For Reference :
http://blog.sqlauthority.com/2007/12/20/sql-server-distinct-keyword-usage-and-common-discussion/
http://weblogs.sqlteam.com/jeffs/archive/2007/10/12/sql-distinct-group-by.aspx
I'm pretty sure it's this:
SELECT DISTINCT(Suppliers.SupplierID), Customers.CompanyName, Products.ProductName,Orders.OrderDate
FROM Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate <='1/1/1999'
ORDER BY Suppliers.SupplierID

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