Retrieve columns from three tables - mysql

I want to use columns from three different tables and use them to calculate how much each customer has ever spent.
tblCustomer(CustomerID)
tblOrder(CustomerID, ProductID, Amount)
tblProduct(ProductID, Price)
So I want to filter out the orders made by a customer, check what product they ordered and what amount of it, check the price and multiply it with the amount they ordered and do that with every customer
expected result:
CustomerID | TotalSpent
1|20
2|130

This depends on the relationship between the tables. The below assumes there is only one price per product in the price table. The customer table is excluded as it is unnecessary but could be joined again using the customerID
SELECT tblOrder.CustomerID,
SUM(tblOrder.Amount*tblProduct.Price) AS 'TotalSpent'
FROM tblOrder JOIN tblProduct ON tblProduct.ProductID = tblOrder.ProductID
GROUP BY tblOrder.CustomerID

Related

Multiple the amount of sold products with the price of the product

My tables look like this:
tblartikel(artikelid primary key, price)
tblbestallning(artikelid, amount)
I saw someone do this:
select artikelid, sum(amount) as AmountSold from tblbestallning group by artikelID
this correctly showed the artikelid's and thee amount it has ever been bought
how do i multiply the times it has been bought with the price?
This depends on the relationship between the two tables but assuming there is only one price per artikel, this would be a good starting point
SELECT tblbestallning.artikelid,
SUM(amount) as AmountSold,
SUM(amount*price) AS 'TotalSold'
FROM tblbestallning
JOIN tblartikel ON tblartikel.artikelid = tblbestallning.artikelid
GROUP by tblbestallning.artikelid

Got orders and order_products tables.Should total price of order be stored in the orders table, or calculated based on the products quantity and price

So I have the following 3 tables:
Table: Products
Columns: id, name, description, price, currency
Table: Orders
Columns: id, firstName, lastName, phoneNumber
Table: Order_Products
Columns: orderId, productId, quantity
Now I'm trying to figure out where to put the total price of the order and I have 2 ideas:
Add a totalPrice column to the Orders table that will contain the sum of the price * quantity of all products in the order, or:
Add a price column to the Order_Products table that will contain the the price * quantity of that specific product, and then I'd have to get all Order_Products records for that order and sum their price columns.
I'm not quite sure which option is better, hence why I'm asking for recommendations here.
I would recommend that you store the order total in the orders table.
Why? Basically, order totals are not necessarily the same as the sum of all the prices on the items:
The prices might change over time.
The order itself might have discounts.
In addition, the order might have additional charges:
Discounts applied to the entire order.
Taxes.
Delivery charges.
For these reasons, I think it is safer to store financial information on the order when the order is placed.
I woulnd't recommend storing this. This is derived information, that can be computed on the fly whenever needed. If you are going to do the computation often, you can use a view:
create view orders_view as
select o.*, sum(p.price * op.quantity) total_price
from orders o
inner join order_products op on op.orderid = o.id
inner join products p on p.id = op.productid
group by o.id

Get correct details when using MAX() function in mySQL

So I have two mySQL tables: products and prices. In products I have the informations about the product (id, name, type, date,...) and prices include informations for the prices for a products. i.E. product USB with ID CF003X from table products is available in tableprices with sellers (A, B, C and prices 18.00, 12.00, 13.50).
Now, when I want to select the highest price for a date, groupped by product IDs, the query returns the highest prices, but doesnt show correctly from which seller.
I also want to get results where i.E. seller 'Asus' had the highest price1
SQL Fiddle
This is a typical example where subqueries can be used: create a subquery that returns the highest price for product in a certain data range, then join this back to the prices table and get the supplier(s) who supply at that price. The date range, however, should probably be in the prices table, not in the products one. Prices change, products not really (they can be flagged as not to be listed). You should also consider having a product and a pricing id in the pricing table.
However, I'm going along with the fields you supplied within the sqlfiddle example.
select prod.id, p.seller, p.price1, p.price2
from prices p
inner join (select id, max(price1) as maxprice from prices group by id) mp on p.id=mp.id and p.price1=mp.maxprice
inner join products prod on p.id=prod.id
where prod.date='...'
You can extend the above query to show a specific vendor only by adding that vendor to the where criteria.

Comparing an integer field in each record of a table to the sum of associated records in another table

Let's say I have these two tables: Product and Storage
Product has a ProductId, and a QuantityAvailable for each record
Storage has a LocationId, ProductId and QuantityAvailable for each record (ProductId is a FK to the product table). A 'ProductId' can be stored in multiple 'LocationId's, therefore ProductId and LocationId make up a compound primary key.
What I want is an SQL query that is able to determine if a 'Product' is in storage, and if so, if the 'Quantity' in cumulative storage is less than the 'QuantityAvailable'.
To put things simply, I want a listing of all the 'ProductId's in the Product table where the sum of the 'Quantity' of all the associated entries in the Storage table is less than the 'QuantityAvailable' of the Product Table.
How can I achieve this (without changing the table structure)?
thanks
The following query will give you the sum of the quantities for each product:
select ProductID, sum(Quantity) as ProductQuantity
from
Storage
group by
ProductID
Now you simply need to use that query as a derived table, join to it, and compare your 2 quantities:
select
*
from
Product p
inner join (
select ProductID, sum(Quantity) as ProductQuantity
from
Storage
group by
ProductID) q
on p.ProductID = q.ProductID
where
q.ProductQuantity < p.QuantityAvailable

Calculate value from two field in third field

I'm trying to create a query, that will calculate sum of products on invoice. I have 3 tables :
Product (with product's price)
Invoice (with invoice id)
Products on invoice (with invoice id, product id and number of particular products)
So in my query I take invoice_id (from invoice), price (from product),number of products sold and invoice_id (from products on invoice) and calculate their product in fourth column. I know I should use 'Totals' but how to achieve that ?
The following added to your SELECT should do it.
[Product].[price] * [Products on invoice].[number of products on invoice] AS Total
If you include the fields and table names, I can give you a much more accurate statement.
Edit:
SELECT
invoice.invoice_id,
product.price,
products_on_invoice.amount,
product.price * products_on_invoice.amount AS Total
FROM
invoice INNER JOIN
(products_on_invoice INNER JOIN
product
ON products_on_invoice.product_id = product.product_id)
ON invoice.invoice_id = products_on_invoice.invoice_id