How to use Max function on another column from a select - sql

There is query which is asking for favourite products which is bought by each coustomer. i have to select and in the first select i have selected the count of products that each customer bought. in the other select i want to select the maximum of that boughts for each customer.but when i want to select max(previous select column) it gets and error and says it is not defined can any one helps me how to fix this problem. i am very motivated to solve the problem from this way, and i am not willing to use other methods like creating view or something like that. can any one help me on this:
SELECT INN.Maximum,INN.Name, customer.ProductName from
(SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
FROM Orders, [Order Details], Products, Customers
WHERE [Order Details].OrderID = Orders.OrderID
AND [Order Details].ProductID = Products.ProductID
AND Orders.CustomerID = Customers.CustomerID
GROUP BY ContactName, ProductName)customer
INNER JOIN
(SELECT Customers.ContactName AS Name, **MAX(customer.numOftimecustomer)** AS Maximum
from Customers, customer
GROUP BY Customers.ContactName) INN
ON INN.Name = customer.ContactName AND INN.Maximum = customer.NumOftimeCustomer
that part which is mentioned with MAX(customer.numOftimecustomer) ** is the part which gives error and it says the object customer is not defined. is there a way to solve it without view? why is it in this way? since the customer that i defined is not a table?

here is what you want:
select
*
from (SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
FROM Orders, [Order Details], Products, Customers
WHERE [Order Details].OrderID = Orders.OrderID
AND [Order Details].ProductID = Products.ProductID
AND Orders.CustomerID = Customers.CustomerID
GROUP BY ContactName, ProductName)customer
where customer.num = (select max(num) from
(SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
FROM Orders, [Order Details], Products, Customers
WHERE [Order Details].OrderID = Orders.OrderID
AND [Order Details].ProductID = Products.ProductID
AND Orders.CustomerID = Customers.CustomerID
GROUP BY ContactName, ProductName)customer2
where customer2.name = customer.name)

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'

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

Getting data from a JOIN in SQL

Sorry for the messy name of the question, this is my first SQL one.
Does anyone know how to get the OrderID of an Order where the max quantity of a product was sold?
This is my code by far:
SELECT Products.ProductName, MAX([Order Details].Quantity), MAX(OrderID)
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID
GROUP BY Products.ProductName
When I say MAX(OrderID) I get the Highest ID where the product was sold, not the actual ID where the Highest quantity of the product was sold.
This is my first question about SQL, Sorry for any lack of information, just tell me what is needed and I'll add it. Thanks in advance!
EDIT: I'm using SQL Server 2008
You can use analytical functions for this:
UPDATED
SELECT ProductName, Quantity, OrderID
FROM ( SELECT Products.ProductName, [Order Details].Quantity, OrderID,
ROW_NUMBER() OVER(PARTITION BY Products.ProductName ORDER BY [Order Details].Quantity DESC) Corr
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID) A
WHERE Corr = 1
This way you will get only one record per Product, that means that if you have more than one Order with the same max quantity, you are only getting one as result. You can add more columns (order date for example) on the ORDER BY to choose the newest or oldest of those. If you want to get all the records that are tied on the quantity, then you can use RANK instead of ROW_NUMBER.
SELECT ProductName, Quantity, OrderID
FROM ( SELECT Products.ProductName, [Order Details].Quantity, OrderID,
RANK() OVER(PARTITION BY Products.ProductName ORDER BY [Order Details].Quantity DESC) Corr
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID) A
WHERE Corr = 1
SELECT Products.ProductName, [Order Details].OrderID, [Order Details].Qty
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID
WHERE [Order Details].Quantity = (SELECT MAX(p.Quantity) FROM [Order Details] p WHERE p.ProductID = Products.ProductID)
Note: this will give you multiple results for a single product, if you have multiple orders with max quantity ordered.

how to work with Derived Tables

I am trying to understand a derived tables I kinda have an idea but still messing with it. I did this code that I dont think is right. I don't know if I have something input wrong or left something out. The table I am working with is a distinct company name from the customers table where the orders have a higher discount than.2.I have been looking over it maybe I have some of the names backwards or something.
SELECT DISTINCT c.CompanyName
From Customers As c
Join
(Select OrderID
From Orders as o
Join [Order Details] as od
ON c.Customers = od.OrderID
Where od.OrderID = '<.2'
The last Part is not working so well with the.2
How the columns are set up in the northwind database you click on tables and go down to see the dbo.Order Details and click on columns you will find OrderId, ProductID, UnitPrice, Quantity, Disounts. Then you will have the Custumers table which had CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, COuntry, Phone, and Fax. Now if you go under the order table you will have OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate,ShipVia, Frieght, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry.
Something like this should do it.
SELECT c.CompanyName
FROM Customers c
WHERE EXISTS(SELECT NULL
FROM Orders o
INNER JOIN [Order Details] od
ON o.OrderID = od.OrderID
AND od.Discount > .2
WHERE o.CustomerID = c.CustomerID)