How to multiply 2 columns and then SUM the results? - sql

I'm learning SQL and I couldn't find the solution to my problem anywhere on he forums. Anyway, I'm using a www.dofactory.com SQL Sandbox and I've made a query:
select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*Product.UnitPrice AS "Quantity x UnitPrice"
FROM Customer
JOIN [Order] ON [Order].CustomerID = Customer.ID
JOIN OrderItem ON OrderItem.OrderId = [Order].ID
JOIN Product ON Product.Id = OrderItem.ProductId
where
[Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])
And result:
LastNam ProductName Quantity UnitPrice Quantity x UnitPrice
Kloss Côte de Blaye 60 263.50 15810.00
Kloss Chartreuse verte 80 18.00 1440.00
Now I want to SUM the whole Column "Quantity x UnitPrice". What should I do?

You use SUM(). Something like this:
SELECT SUM(oi.Quantity * oi.UnitPrice) AS Summary
FROM Customer c JOIN
[Order] o
ON o.CustomerID = c.ID JOIN
OrderItem oi
ON oi.OrderId = o.ID JOIN
Product p
ON p.Id = oi.ProductId
WHERE o.TotalAmount = (select max(o2.TotalAmount) FROM [Order] o2);
Note the use of table aliases. They make the query easier to write and to read.

This is SQL Server (T-SQL). You can use SUM and GROUP BY like so. I've done it in a subquery, which is how I'd approach this sort of thing.
select LastName, ProductName, Quantity, UnitPrice, SUM(Summary)
from (
select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*OrderItem.UnitPrice AS Summary, [Order].TotalAmount
FROM Customer
JOIN [Order] ON [Order].CustomerID = Customer.ID
JOIN OrderItem ON OrderItem.OrderId = [Order].ID
JOIN Product ON Product.Id = OrderItem.ProductId
where
[Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])) x
group by LastName, ProductName, Quantity, UnitPrice

Related

SQL number of products bought by at least 5 unique customers

I have a database with following objects:
Price (prodID, from, price)
Product (prodID, name, quantity)
PO (prodID, orderID, amount)
Order (orderID, date, address, status, trackingNumber, custID, shipID)
Shipping (shipID, company, time, price)
Customer (custID, name)
Address (addrID, custID, address)
I am trying to return the names of products ordered by at least 5 different customers. My code is:
SELECT Product.name, COUNT(DISTINCT custId) as cust_count
FROM Product P
INNER JOIN PO
ON PO.prodId = P.prodId
INNER JOIN "Order" O
ON O.orderId = PO.orderId
INNER JOIN Customer C
ON C.custId = O.custId
HAVING COUNT(DISTINCT custId) > 4;
I am getting the following errors:
The multi-part identifier "Product.name" could not be bound" Ambiguous column name 'custID'
You need a GROUP BY -- and to use your table aliases:
SELECT p.name, COUNT(DISTINCT o.custId) as cust_count
FROM Product P INNER JOIN
PO
ON PO.prodId = P.prodId INNER JOIN
"Order" O
ON O.orderId = PO.orderId
GROUP BY p.name
HAVING COUNT(DISTINCT o.custId) > 4;
Note that the JOIN to Customer is not necessary because the id is in the Order table.
You also try this.I hope this will solve your problem
SELECT DISTINCT TOP (5) o.custId, p.name
FROM Order O INNER JOIN
PO
ON PO.orderID = O.orderID INNER JOIN
Product P
ON P.prodID = PO.prodID

Stuck doing a common table expression to calculate total orders for each product category using NORTHWND

Guys so as part of my job as a Data Support Analyst I am training up to become a software developer, my mentor gave me a group of test statements and this one seems way more advanced than anything I have done previously. The question is...
*
6) Write a subquery or common table expression to calculate total
orders for each product category. that will Write a query that will
bring back each product name, the total number of orders made for the
product and join to the subquery or CTE to calculate the percentage
of sales that product represents of its product category. For example,
if Category of Soaps has 2 products; Blue Soup and Red Soap, blue soup
had 40 orders and red soaps had 10 orders I would expect to see the
following rows: Product Name Total Orders % of Category Red
Soap 40 80%
Blue Soap 10 20%
*
So far I have managed to get the following but I'm struggling to progress past this...
;WITH [Products] (CategoryId, TotalNumberOfOrders)
AS (
SELECT p.CategoryId,
COUNT (OD.OrderID) as TotalNumberOfOrders
FROM [dbo].[Products] p
INNER JOIN [dbo].[Order Details] OD
ON p.ProductID=OD.ProductID
GROUP BY p.CategoryId )
SELECT * From Products
Any help would be fantastic! ( I'm using NORTHWND database btw)
I think what you need is
;WITH temp AS
(
SELECT p.CategoryId,
COUNT (DISTINCT OD.OrderID) as TotalNumberOfOrders
FROM [dbo].[Products] p
INNER JOIN [dbo].[Order Details] OD ON p.ProductID=OD.ProductID
GROUP BY p.CategoryId
)
SELECT p.ProductName,
Count(DISTINCT Od.OrderId) AS Total,
Count(DISTINCT Od.OrderId)*100/temp.TotalNumberOfOrders AS Percentage
FROM Products p
INNER JOIN [dbo].[Order Details] OD ON p.ProductId = OD.ProductId
INNER JOIN temp ON p.CategoryId = temp.CategoryId
GROUP BY p.ProductId, p.ProductName, temp.TotalNumberOfOrders
Remember Count(Distinct..) to count Order.
Using a sub-Query:
SELECT P.ProductName,
COUNT(OrderID) AS NumberOfOrders,
CAST((CAST(COUNT(OrderID) AS DECIMAL(9,2)) / CAST(Derived_Table.CNT AS
DECIMAL(9,2))) * 100 AS DECIMAL(9,2)) AS Percentage
FROM [Northwind].[dbo].[Order Details]
INNER JOIN dbo.Products AS P
ON [Order Details].ProductID = P.ProductID
INNER JOIN (SELECT COUNT(F.OrderID) AS CNT, P.CategoryID
FROM [Northwind].[dbo].[Order Details] F
INNER JOIN dbo.Products P
ON F.ProductID = P.ProductID
GROUP BY P.CategoryID) AS Derived_Table
ON P.CategoryID = Derived_Table.CategoryID
GROUP BY [Order Details].ProductID, P.ProductName, Derived_Table.CNT
ORDER BY [Order Details].ProductID

Finding Customers Last Price Paid

I'm trying to find a way to get customers last price paid the code we have at the moment is:
SELECT Product.ProductCode,
COUNT(Product.ProductCode) AS [Qty Baught],
Product.Description,
Customer.CustomerCode,
Customer.Name,
MAX(OrderHeader.DateTimeCreated) AS [Date],
OrderLine.UnitSellPriceInCurrency AS Sell
FROM Customer
INNER JOIN OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
INNER JOIN OrderLine ON OrderHeader.OrderID = OrderLine.OrderID
INNER JOIN Product ON OrderLine.ProductID = Product.ProductID
GROUP BY Product.Description,
Product.ProductCode,
Customer.CustomerCode,
Customer.Name,
OrderLine.UnitSellPriceInCurrency
HAVING (Product.ProductCode = 'bcem002')
AND (Customer.CustomerCode = '1000')
ORDER BY MAX(OrderHeader.DateTimeCreated) DESC
This code shows every time the price changed but I only want to see the last price, But the DateCreated and the price paid (UnitSellPriceInCurrency) are on different tables.
Is there a way to Group (UnitSellPriceInCurrency) by (DateCreated) or an alternative way of doing it.
I'm fairly new at this so if there's an obvious way of doing this sorry.
Edit: What i'm getting at the moment with new code, Most of the prices i'm getting up are unrelated to the products
What I want is to get just the last price paid showing but in a way I can change the customer and the product that I'm searching for.
One option might be to use a sub-select utilizing TOP to specify that you only want to retrieve one record, and make sure that it is the "latest" by using the ORDER BY:
SELECT Product.ProductCode,
COUNT(Product.ProductCode) AS [Qty Baught],
Product.Description,
Customer.CustomerCode,
Customer.Name,
MAX(OrderHeader.DateTimeCreated) AS [Date],
(SELECT TOP 1 O.UnitSellPriceInCurrency
FROM OrderLine O
INNER JOIN OrderHeader OH ON O.OrderID = OH.OrderID
WHERE OH.CustomerID = Customer.CustomerID AND O.ProductID = Product.ProductID
ORDER BY OH.DateTimeCreated DESC) AS LatestPrice
FROM Customer
INNER JOIN OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
INNER JOIN OrderLine ON OrderHeader.OrderID = OrderLine.OrderID
INNER JOIN Product ON OrderLine.ProductID = Product.ProductID
WHERE (Customer.CustomerCode = '1000') AND (Product.ProductCode = 'bcem002')
GROUP BY Product.Description,
Product.ProductCode,
Product.ProductID,
Customer.CustomerCode,
Customer.Name,
Customer.CustomerID
ORDER BY [Date] DESC
In this example LatestPrice will contain the last inserted UnitSellPriceInCurrency for each Customer and product. I'm not sure if the query makes sense with your data (why get only the last price) but it's how I interpreted your request. The query will still return all OrderHeaders though.
Can you please check of this works alright. It would be better if you posted a snapshot of the current result and the expected result you need.
Select
*
FROM
(
SELECT Product.ProductCode,
COUNT(Product.ProductCode) AS [Qty Baught],
Product.Description,
Customer.CustomerCode,
Customer.Name,
OrderHeader.DateTimeCreated AS [Date],
OrderLine.UnitSellPriceInCurrency AS Sell
RANK() OVER (PARTITION BY Customer.CustomerCode,Customer.Name, OrderLine.UnitSellPriceInCurrency ORDER BY OrderHeader.DateTimeCreated) rnk
FROM Customer
INNER JOIN OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
INNER JOIN OrderLine ON OrderHeader.OrderID = OrderLine.OrderID
INNER JOIN Product ON OrderLine.ProductID = Product.ProductID
WHERE Product.ProductCode = 'bcem002'
AND Customer.CustomerCode = '1000'
GROUP BY Product.Description,
Product.ProductCode,
Customer.CustomerCode,
Customer.Name,
OrderLine.UnitSellPriceInCurrency
) tbl1
WHERE tbl1.rnk =1
;

Add duplicate values in a table sql server

Select
P.ProductName, WFS.Status, OI.Quantity, OI.Price
from
OrderItem As OI
Inner Join
Order As O On OI.OrderID = O.ID AND OI.ItemType = 1
Inner Join
Product P On OI.ProductID = P.ID
Inner Join
WorfFlowStatus As WFS On O.StatusID = WFS.ID
This query returns the rows:
ProductName Status Quantity Price
-------------------------------------------
ABC Shipped 10 100
ABC Shipped 10 100
BCE Pending 20 200
Now I want to select the same product in one row but quantity and price should be added. For e.g
ABC Shipped 20 200
BCE Pending 20 200
If status and productname is same than add the quantity and price and if product is not the same then no addition in quantity and price.
Select
P.ProductName,
WFS.Status,
sum(OI.Quantity),
sum(OI.Price)
from OrderItem As OI
Inner Join Order As O
On OI.OrderID = O.ID AND OI.ItemType = 1
Inner Join Product P
On OI.ProductID = P.ID
Inner Join WorfFlowStatus As WFS
On O.StatusID = WFS.ID
group by
P.ProductName,
WFS.Status
As pointed out by cha, the Group By clause is the key:
Select P.ProductName,WFS.Status,sum(OI.Quantity),sum(OI.Price)
from OrderItem As OI
Inner Join [Order] As O On OI.OrderID = O.ID AND OI.ItemType = 1
Inner Join Product P On OI.ProductID = P.ID
Inner Join WorkFlowStatus As WFS On O.StatusID = WFS.ID
group by productName, Status
'over with Partition by' can help.
For example
select ProductName,
Status,
Quantity,
(SUM(Quantity) OVER (PARTITION BY ProductName)) as TotalQuantity
FROM YourTableName and joins
select P.ProductName, WFS.Status, sum(OI.Quantity), sum(OI.Price)
from OrderItem OI, Order O, Product P, WorkFlowStatus WFS
where OI.OrderID = O.ID and OI.ItemType = 1 and
OI.ProductID = P.ID and
O.StatusID = WFS.ID
group by productName, Status

SQL selection criteria on grouped aggregate

I'm trying to find a simple MySQL statement for the following two problems:
I have 4 tables: Employees, Customers, Orders, Products (Each entry in Orders contains a date, a reference one product, a quantity and a reference to a customer, and a reference to an Employee).
Now I'm trying to get all customers where the volume of sale (quantity * product.price) is bigger in 1996 than in 1995.
And: I want to list all Employees whose volume of sale is below the average volume of sale.
Any help would really be appreciated. I've managed to get the information using a php script but I think this can be done with some clever SQL Statements.
Can anybody help me?
Employee Table: ID# Name
Products Table: ID# NAME# PRICE
Orders Table: ODERID# CUSTOMERID # DATE # EMPLOYEE# PRODUCTID# QUANTITY
For the first part (assuming quite a bit about the schema):
SELECT Customers.ID
FROM Customers
LEFT JOIN orders AS o1 ON o1.CustomerID=Customers.ID AND YEAR(o1.DATE) = 1995
LEFT JOIN products AS p1 ON p1.id = o1.productID
LEFT JOIN orders AS o2 ON o2.CustomerID=Customers.ID AND YEAR(o2.DATE) = 1996
LEFT JOIN products AS p2 ON p2.id = o2.productID
HAVING SUM(o1.quantity* p1.price) < SUM(o2.quantity*p2.price)
I don't know the database type you're using, so I'll use sqlserver. The 'Year' function is available on most databases, so you should be able to rewrite the query for your db in question.
I think this is the query which returns all customerid's + ordertotal for the customers which have a higher total in 1996 than in 1995, but I haven't tested it. Crucial is the HAVING clause, where you can specify a WHERE kind of clause based on the grouped result.
SELECT o.CustomerId, SUM(o.Quantity * p.Price) AS Total
FROM Orders o INNER JOIN Products p
ON o.ProductId = p.ProductId
WHERE YEAR(o.Date) == 1996
GROUP BY o.CustomerId
HAVING SUM(o.Quantity * p.Price) >
(
SELECT SUM(o.Quantity * p2.Price) AS Total
FROM Orders o2 INNER JOIN Products p2
ON o2.ProductId = p.ProductId
WHERE YEAR(o.Date) == 1995
AND o2.CustomerId = o.CustomerId
GROUP BY o.CustomerId
)
something like that:
select * from customers c
where (select sum (o.quantity * p.price) from orders o, product p where o.productID = p.productID and o.dateyear = 1996 and o.customerID = c.customerID) < (select sum (o.quantity * p.price) from orders o, product p where o.productID = p.productID and o.dateyear = 1995 and o.customerID = c.customerID)
select * from employees e where (select avg (o.quantity * p.price) from orders o, product p where o.productID = p.productID and o.empID = e.EmpID) < (select avg (o.quantity * p.price) from orders o, product p where o.productID = p.productID)