How to get the Total Amount Each Customer Has Spent - sql

I am making a database for a simple purchase, customer, employee, etc tables.
I am making a query that includes all of the employees who have boughten something, along with some of their data, and then the last field is supposed to have the total amount that they have boughten. However, I am not too sure on how to achieve this.
I am not quite sure on how to get the total to be almost like a sub-query to total up what the customer has gotten. For instance, the first 5 rows should have a total of 180.40.
I have been looking online for some help with totaling queries but couldn't find any good examples.
Any help would be wonderful! Thank you (I am pretty new to SQL and Access)!
Edit: Forgot to add this!
SELECT Employee.FirstName, Employee.LastName, Purchase.PurchaseID, Product.ProductName, Product.Price, Product.Price AS Total
FROM Employee
INNER JOIN (Customer INNER JOIN (Product INNER JOIN Purchase ON Product.ProductID = Purchase.ProductID)
ON Customer.CustomerID = Purchase.CustomerID) ON Employee.EmployeeID = Customer.EmployeeID;

Do you just want aggregation?
SELECT e.FirstName, e.LastName,
SUM(p.Price)
FROM ((Employee as e INNER JOIN
Customer as c
ON e.EmployeeID = c.EmployeeID
) INNER JOIN
Purchase pu
ON c.CustomerID = pu.CustomerID
) INNER JOIN
Product as p
ON p.ProductID = pu.ProductID
GROUP BY e.FirstName, e.LastName;

Related

Creating a table view for invoice - Northwind

I have a little problem with my last tasks. I am using an old Northwind database.
First, I had to create a query, that will give me all the important information for the invoice. My query looks like this:
SELECT b.OrderID,
b.CustomerID,
c.CompanyName,
c.Address,
c.City,
c.PostalCode,
c.CountryID as CustomersCountryID,
concat(d.FirstName, ' ', d.LastName) as Salesperson,
a.CompanyName as ShippingVia,
e.ProductID,
f.ProductName,
e.Quantity,
e.UnitPrice * e.Quantity * (1 - e.Discount) as ExtendedPrice
from Shippers a
inner join Orders b on a.ShipperID = b.ShipVia
inner join Customers c on c.CustomerID = b.CustomerID
inner join Employees d on d.EmployeeID = b.EmployeeID
inner join [Order Details] e on b.OrderID = e.OrderID
inner join Products f on f.ProductID = e.ProductID
order by b.OrderID
It works, it gives me all the orders made with informations. But now, I need to create a table view for an invoice of particular OrderId. When I write something like this:
CREATE VIEW FAKTURA AS
SELECT b.OrderID,
b.CustomerID,
c.CompanyName,
c.Address,
c.City,
c.PostalCode,
c.CountryID as CustomersCountryID,
concat(d.FirstName, ' ', d.LastName) as Salesperson,
a.CompanyName as ShippingVia,
e.ProductID,
f.ProductName,
e.Quantity,
e.UnitPrice * e.Quantity * (1 - e.Discount) as ExtendedPrice
from Shippers a
inner join Orders b on a.ShipperID = b.ShipVia
inner join Customers c on c.CustomerID = b.CustomerID
inner join Employees d on d.EmployeeID = b.EmployeeID
inner join [Order Details] e on b.OrderID = e.OrderID
inner join Products f on f.ProductID = e.ProductID
WHERE b.OrderID = 10248
I am just creating a separate view file for that particular OrderID. It doesn't look like a real life invoice at all.
It should resemble something like this:
I need to separate general data about invoice and customer from data about order itself, product ID, quantity etc.
Is it possible to create something similar in SQL Server Management Studio? How can I do it?
Your query already provides the header (customer info) and table body parts, so what you could do is (NOTE: this is NOT what I would do but, considering the need to have a very simple solution):
Phrase a query that would perform all the needed calculations for the trailing part based on the INVOICE number (this can be similar to what you already have except that it would SUM the amounts, calculate taxes and shipping cost),
Once you have that query ready, INNER JOIN it to the one you already have (using the invoice ID as a key); Note that you will have to add the additional fields to the top SELECTs list.
The result will be what you already have + the subtotal, tax, shipping and total in each and every record.
Again, this is NOT the most efficient and elegant solution, but matches your needs (simplicity and final result).

SQL Server Aggregation using Max() and obtaining details from max() line.

I just took a final exam and one of the questions asked me to double join three tables, and report the max sale payout for each salesperson.
The tables have the following variables:
Salesperson(id, name)
Order(orderid, order_date, Cust_id, Saleperson_id, amount)
Customer(id, name)
After joining:
select salesperson.Name, Orders.Number, customer.Name, Orders.Amount
from Orders
join salesperson
on orders.Salesperson_id = salesperson.ID
join Customer
on customer.ID = orders.cust_id
What the instructed wanted was for me to find each salesperson's maximum sell (as found by order.amount). He also wanted the salesperson (salesperson.name), the order number of the max sale (orders.number), the customer the sale was with (customer.name), and the max sale amount. What is the most efficient way to do this problem? I have tried to use "group by salesperson.name", but I cannot because the orders.number and customer.name are never held in the aggregation.
I finished the problem this way
select
salesperson.name as Sales_Person,
orders.number as Order_Number,
customer.Name as Customer_Name,
orders.Amount as Sale_Amount
from salesperson
left join Orders
on salesperson.ID = orders.Salesperson_id
left join Customer
on orders.cust_id = customer.ID
where orders.Amount in (select max(orders.Amount)
from salesperson
join Orders
on salesperson.ID = orders.Salesperson_id
join Customer
on orders.cust_id = customer.ID
group by salesperson.name)
I know this is a bad way to do it. For instance, what if two different salesperson's max sale was equivalent? Max and min are not like count and sum because it is picking out one line from a aggregation, but the rules still apply. Also, you might notices that there is no real unique identifier in the joined table other than order.number which is not useful. Therefore, I would have to use some composite of salesperson.name and order.number.
Also, what do I do if I have to pick the top three sales for each salesperson? Should such an output be totally different code-wise than what would be required from just the first sale?
I keep bumping me head against this problem, and I would love to have a more professional approach to this problem.
SELECT
M.max_amount,
S.Name,
O.Number,
C.Name
FROM orders O
JOIN salesperson S
ON S.Salesperson_id = O.Salesperson_id
JOIN customer C
ON C.Customer_id = O.Customer_id
JOIN (
SELECT Salesperson_id, MAX(amount) max_amount
FROM Order
GROUP BY Salesperson_id
) M
ON M.Salesperson_id = O.Salesperson_id AND M.max_amount = O.amount
For the top 3:
SELECT
M.Amount,
S.Name,
O.Number,
C.Name
FROM orders O
JOIN salesperson S
ON S.Salesperson_id = O.Salesperson_id
JOIN customer C
ON C.Customer_id = O.Customer_id
CROSS APPLY (
SELECT TOP 3 Amount
FROM Order
WHERE Salesperson_id = O.Salesperson_id
ORDER BY Amount DESC
) M

Oracle: Using Sub-Queries, JOIN and distinct function together

Here is how I contructed the step-by-step:
M1. create a sub-query that will return CustomerId and total invoiced for that customer
M2. A second subquery that will give a list of distinct ProductIDs (along with product SKUs) and CustomerIDs.
M3. The M1 and M2 subqueries will be joined to make association between customer totals and products (for the same CustomerId).
M4. The query M3 will be fed to the final query that will just find the top 5 products.
I'm stuck on creating the distinct ProductID and customerID because they would have to be in aggregate functions in order to make them distinct.
Attached is an image that is the erwin diagram which helps understand the system.
If you can help me with M1-M4, I will greatly appreciate it. I'm not a programmer by trade but a business analyst.
--M1--
select C.CustomerId, COUNT(I.InvoiceId) TotalNumInvoices
from Customer C
JOIN Invoice I ON (I.CustomerId = C.CustomerId)
group by C.CustomerId
--M2: Incomplete--
select P.ProductID, P.SKU, C.CustomerID
from Product P
JOIN InvoiceLine IL ON (IL.ProductId = P.ProductId)
JOIN Invoice I ON (IL.InvoiceId = I.InvoiceId)
JOIN Customer C ON (C.CustomerId = I.CustomerId)
you can also use the DISTINCT keyword your select clause in order to get unique values. Try this for m2:
select DISTINCT p.productID, p.sku, i.customerID
from invoice i INNER JOIN invoiceLine il
ON i.invoiceID = il.invoiceID
JOIN product p
ON il.productID = p.productID;

Join between two master and one detail Table

I am working with Northwind Data Base(Microsoft Example) and i want to know total Sale of each Region.
tables for this example are (Region,Territories,EmployeeTerritories,Employees,Orders and OrderDetails)
And relations are:
Region on to many Territories
Territories on to many EmployeeTerritories
EmployeeTerritories many to one Employees
Employees on to many Orders
Orders one to many OrderDetails
i know that i should to use Sub query but i dont know how.
select
*
from
Region R
inner join Territories T
on R.RegionID=T.RegionID
inner join EmployeeTerritories ET
on T.TerritoryID=ET.TerritoryID
inner join
(
select
E.EmployeeID,
E.FirstName,
E.LastName,
sum(OD.Quantity*OD.UnitPrice) as TotalEmployeeSale
from
Employees E
inner join Orders O
on E.EmployeeID=o.EmployeeID
inner join [Order Details] OD
on o.OrderID=OD.OrderID
Group by
E.EmployeeID,
E.FirstName,
E.LastName
)as ES on ET.EmployeeID=ES.EmployeeID
I use this sql query to calculate Total sale for Each Employee but how can i Caclulate is for Each Region.
Haven't got access to Northwind right now, so this is untested, but you should get the idea...
There's no need to get data about employees if all you want is sales per region. Your subquery is therefore redundant...
select
r.RegionDescription,
sum(OD.Quantity*OD.UnitPrice)
from
Region R
inner join Territories T
on R.RegionID=T.RegionID
inner join EmployeeTerritories ET
on T.TerritoryID=ET.TerritoryID
inner join Employees E
on ET.EmployeeID=E.EmployeeID
inner join Orders O
on E.EmployeeID=o.EmployeeID
inner join [Order Details] OD
on o.OrderID=OD.OrderID
Group by r.RegionDescription
As discussed in the comments, this "double counts" sales where an employee is assigned to more than one region. In many cases, this is desired behaviour - if you want to know how well a region is doing, you need to know how many sales came from that region, and if an employee is assigned to more than one region, that doesn't affect the region's performance.
However, it means you overstate the sales if you add up all the regions.
There are two strategies to avoid this. One is to assign the sale to just one region; in the comments, you say there's no data on which to make that decision, so you could do it on the "lowest regionID) - something like:
select
r.RegionDescription,
sum(OD.Quantity*OD.UnitPrice)
from
Region R
inner join Territories T
on R.RegionID=T.RegionID
inner join EmployeeTerritories ET
on T.TerritoryID=ET.TerritoryID
inner join Employees E
on ET.EmployeeID=E.EmployeeID
inner join Orders O
on E.EmployeeID=o.EmployeeID
inner join [Order Details] OD
on o.OrderID=OD.OrderID
Group by r.RegionDescription
having et.TerritoryID = min(territoryID)
(again, no access to DB, so can't test - but this should filter out duplicates).
Alternatively, you can assign a proportion of the sale to each region - though then rounding may cause the totals not to add up properly. That's a query I'd like to try before posting though!

TSQL basic join on Northwind database

I am learning TSQL (well, just SQL to tell the truth) and I want to make Employee - Product statistic on Northwind database.
Expected results should be something like:
EmployeeID | ProductID | income
1 | 1 | 990
1 | 2 | 190
1 | 3 | 0
...
For all Employy-Product pairs
My first try is this query:
SELECT E.EmployeeID, OE.ProductID, SUM(OE.ExtendedPrice) as income
FROM [Order Details Extended] OE
JOIN [Orders] O
ON OE.OrderID = O.OrderID
RIGHT OUTER JOIN Employees E
ON E.EmployeeID = O.EmployeeID
GROUP BY E.EmployeeID, OE.ProductID
ORDER BY E.EmployeeID
But I don't get results for all pairs.
What am I doing wrong?
HLGEM missed few columns but I understood what he tried to do.
I came up with this:
SELECT A.employeeid, A.productid, SUM(Oe.ExtendedPrice) AS income
FROM
(SELECT E.Employeeid, P.productid
FROM employees E
CROSS JOIN products P) A
LEFT JOIN [Order Details Extended] OE
ON A.productid = OE.productid
LEFT JOIN [Orders] O
ON OE.OrderID = O.OrderID
GROUP BY A.EmployeeID, A.ProductID
ORDER BY A.EmployeeID, A.ProductID
This returns results for all pairs, but those don't seem right.
For example above query returns as first row:
1, 1, 12788.10
But this query:
SELECT SUM(ODE.ExtendedPrice) FROM [Order Details Extended] ODE
LEFT JOIN [Orders] OD
ON ODE.OrderID = OD.OrderID
WHERE OD.EmployeeID = 1 AND ODE.ProductID = 1
Returns 990.90.
Why?
edit
I got it finally:
SELECT A.EmployeeId, A.ProductId, ISNULL(SUM(Oe.ExtendedPrice), 0) AS income
FROM
(SELECT E.Employeeid, P.productid
FROM [Employees] E
CROSS JOIN [Products] P) A
LEFT JOIN [Orders] O
ON O.EmployeeID = A.EmployeeID
LEFT JOIN [Order Details Extended] OE
ON A.productid = OE.productid AND OE.OrderID = O.OrderID
GROUP BY A.EmployeeID, A.ProductID
ORDER BY A.EmployeeID, A.ProductID
#HLGEM you can copy/paste this solution to your answer so I can accept it.
You could try:
SELECT A.employeeid,A.product_id, SUM(Oe.ExtendedPrice) AS income
FROM
(SELECT E.Employeeid, P.product id
FROM employee E
CROSS JOIN product p) A
LEFT JOIN [Order Details Extended] OE
ON A.EmployeeID = O.EmployeeID
LEFT JOIN [Orders] O
ON OE.OrderID = O.OrderID
GROUP BY A.EmployeeID, OE.ProductID
ORDER BY A.EmployeeID
I switched it to a LEFT JOIN as most people use them instead of right joins and thus they are easier for maintenance.
What results are you missing? It looks like you have used an inner join between Order Details Extended and Orders, so any orders that don't have details will be excluded. It seems logical that you would want this, since you are summing a value in the details table.
Then you do a right outer join with Employees, so you are including all employees, regardless of whether they have any orders. This also makes sense, since it looks as though you are seeing which employees sold which products.
Your query will only give you the data for products that the employees have actually sold. If you are looking for all employee-product combinations, regardless of whether the employee had ever sold that product, you will want to join the Product table as well, although in my muddled morning, I can't think if you would want an outer join or a cross join.
In all, I think your first try is a good one. Pretty complex for a beginner. Nice effort!