Select aggregate from multiple tables - sql

I have 2 tables which are:
and
I want to select Total Item Line Amount in each Order which is calculated by UnitPrice*Quantity, Total Discount = sum(((Quantity * UnitPrice)/100) * Discount*100) and AverageFreight = (Freight/Total Item In Order) * Total Line Item In Order
I write select statement like this:
select Orders.OrderID,CustomerID, EmployeeID, ProductID,ShippedDate, RequiredDate, ShipVia,(Freight/sum(Quantity))*Quantity 'TotalFreight',
Quantity * UnitPrice 'LineItemTotal',sum(Quantity) 'Line Item Quantity',sum(((Quantity * UnitPrice)/100) * Discount*100) 'Total Line Discount',Discount from Orders
inner join [Order Details] on Orders.OrderID = [Order Details].OrderID
group by Orders.OrderID,Orders.CustomerID, Orders.EmployeeID, [Order Details].ProductID, Orders.RequiredDate, Orders.ShipVia, Orders.Freight, [Order Details].Quantity,[Order Details].UnitPrice, [Order Details].Discount, Orders.ShippedDate
However, it does not calculate the AverageFreight right. What am I doing wrong?

You don't need aggregation for this. A window function should suffice:
select o.*, od.*,
(Freight / order_quantity)*Quantity as AllocatedFreight,
Quantity * UnitPrice as LineItemTotal,
Quantity as [Line Item Quantity],
(((Quantity * UnitPrice)/100) * Discount*100) as [Total Line Discount,
Discount
from Orders o inner join
(select od.*, sum(quantity) over (partition by od.orderId) as order_quantity
from [Order Details] od
) od
on o.OrderID = od.OrderID;

Related

Taking the top 5 suppliers based on sales from Northwind database

How can I take the top 5 suppliers based on sales?
I have the following database:
I have tried multiple solutions this is the closest one but I know it's wrong because of a single supplier appearing more than once.
SELECT TOP 5
(od.UnitPrice * (1 - od.Discount) * od.Quantity) total_sales,
od.Quantity, od.UnitPrice, od.Discount, S.ContactName
FROM
[Order Details] od
INNER JOIN
Products p ON p.ProductID = od.ProductID
INNER JOIN
Suppliers s ON s.SupplierID = p.SupplierID
ORDER BY
total_sales DESC
The sum of the sales is provided by this formula:
SUM(UnitPrice * (1 - Discount) * Quantity)
Any help would be greatly appreciated!
You need to group by supplier
SELECT TOP (5)
s.CompanyName,
s.ContactName,
SUM(od.UnitPrice * (1 - od.Discount) * od.Quantity) total_sales,
FROM
Suppliers s
INNER JOIN
Products p ON s.SupplierID = p.SupplierID
INNER JOIN
[Order Details] od ON p.ProductID = od.ProductID
GROUP BY
s.SupplierID,
s.CompanyName,
s.ContactName
ORDER BY
total_sales DESC;
Note how the primary key of Suppliers is in the grouping even though it is not selected.

Hi i have some problems with a T-SQL using *

Group the ProductID orders, get a total by ProductID, the total of the orders and what represents the ProductID orders of the total order (that is a percentage). Columns Required: PercenofTotal (UnitPrice * Quantity), TotalAmount (UnitPrice * Quantity), PercentofTheTotal (UnitPrice * Quantity)
So this is my code, what i dont know is to do the percentofTheTotal and TotalAmount
SELECT P.ProductID, (P.UnitPrice * ODQuantity) AS tOTALaMOUNTByProductID, (P.UnitPrice * Quantity) as TotalAmount , (P.UnitPrice * OD.Quantity) as PercenofTotal
From Products as P,
From OrderDetails as OD
Group by P.ProductID
you're trying to do something complicated with simple statements that are not correct. Something like this could possibly do what you want to achieve.
USE AdventureWorks2014
GO
SELECT P.ProductID
, SUM(P.StandardCost * OD.OrderQty) AS TotalAmountByProductID
, MAX(SumTA.TotalAmount) AS TotalAmount
, (SUM(P.StandardCost * OD.OrderQty) / (MAX(SumTA.TotalAmount))*100) AS PercentOfTotal
FROM Production.Product as P
INNER JOIN Sales.SalesOrderDetail as OD on P.ProductID = OD.ProductID
LEFT OUTER JOIN (
SELECT max(pid) as pid, SUM(TA.TotalAmount) as TotalAmount
FROM
( SELECT '1' as pid, P.ProductID, SUM(P.StandardCost * OD.OrderQty) AS TotalAmount
FROM Production.Product as P
JOIN Sales.SalesOrderDetail as OD on P.ProductID = OD.ProductID
Group by P.ProductID
)AS TA
) AS SumTA ON SumTA.pid = '1'
Group by P.ProductID
ORDER BY PercentOfTotal Desc

Subquery between three tables using Northwind database with SQL Server

Table [Orders] : OrderID(Primary Key), CustomerID
Table [Order Details] : OrderID(Primary Key), ProductID(Primary Key), Discount
Table [Customers] : CustomerID[Primary Key]
With these three tables, I want to query productID with highest discount for each CustomerID. I need column for ProductID, CustomerID and Discount. How can I solve this problem? All kinds of helps are really appreciated.
Following script I have tried :
select ProductID, a.customerID,
(select MAX(discount)
from [Order Details]
where a.CustomerID=c.customerID
)
from Orders a
join [Order Details]
on a.OrderID=[Order Details].OrderID
join Customers c
on a.CustomerID=c.CustomerID
order by customerID
The following query will return to you the productid with maximum discount for each customer. Please note that if for specific customer, you have more than one product that might have the max discount, I you want to return them, then you need to replace ROW_NUMBER() with DENSE_RANK()
WITH CTE AS
(SELECT ProductID,
o.CustomerID,
Discount,
ROW_NUMBER() OVER(PARTITION BY o.CustomerID ORDER BY Discount DESC) Row_num
FROM [Order Details] od INNER JOIN Orders o
ON od.OrderID= o.OrderID
)
SELECT ProductID,
CustomerID,
Discount
FROM CTE
WHERE Row_num = 1

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.

SQL Query - Understanding the Syntax

I want to display greatest selling product by quantity
Product Table
ProductID ProductName
1 AA
2 BB
3 CC
[Order Details] Table
OrderID ProductID Quantity DateOfOrder
1 1 10 SomeDate
2 1 100 ,,
3 2 15 ,,
4 1 15 ,,
5 2 20 ,,
6 2 30 ,,
7 1 100 ,,
Expected Output
Product By Quantity AA
Because sum(quantity)= 225
I used:
select 'Product By Quantity' + ProductName
from
Products
where ProductID in
(select
ProductID
from
[Order Details] det
where Quantity=
(
select max(SUM(Quantity))
from [Order Details] od
where
od.ProductID=det.ProductID
)
)
I got error : "Cannot perform an aggregate function on an expression containing an aggregate or a subquery"
Please explain me why the syntax fails here so that in future i will write appropriate query by
knowing the correct syntax.Also give me the correct query.
Thank you everybody in advance.
Edit
I was trying for the following query
SELECT 'Best Selling Product'+ProductName
FROM
Products
WHERE ProductID =
(
SELECT ProductID
FROM [Order Details]
GROUP BY ProductID
HAVING SUM(Quantity) = (
SELECT MAX(SQ)
FROM (
SELECT SUM(Quantity) as SQ
FROM [Order Details]
GROUP BY ProductID
) AS OD))
I think this is what you're trying to get to:
select top 1 p.product_name, sum(od.quantity) as total_quantity
from products p
inner join [order details] od
on p.productid = od.productid
group by p.productid, p.product_name
order by total_quantity desc
Try this:
select 'Product By Quantity' + ProductName from Products p
join
(
select top 1 sum(Quantity) sq, od.ProductId
from [Order Details] od
group by od.ProductId
order by 1 desc
) bsp on p.productid = bsp.ProductId
bsp stands for Best Selling Product
looks like select max(SUM(Quantity)) is wrong. The maximum of the sum doesn't have any meaning. Did you mean max(Quantity)?
Try this:
SELECT TOP 1
SUM(o.Quantity)
,p.ProductName
FROM [Order Details] AS o
INNER JOIN [Products] AS p ON p.ProductID = o.ProductID
GROUP BY p.ProductID
,p.ProductName
ORDER BY SUM(o.Quantity) DESC