SUM of multiple products - sql

I'm really struggling with this one. SO I have 2 tables:
Products
PendingCartItems
Here's a screenshot of structure for both tables:
I need to get the SUM for all 3 products WHERE pending_cart_id = 18.
SELECT SUM(price) as TotalCartPrice FROM products WHERE id = '274'
How can I write it so it sums all 3 id's (274+251+49)?

Would something like this not work?
Select sum(b.price*a.quantity)
from pending_cart_items a
join products b
on a.product_id=b.id
where a.pending_cart_id =18
Edit: Just realized I'd omitted the quantity from the cart computation :)

If the model is relational, you can try this
SELECT
SUM(price) as TotalCartPrice
FROM products
INNER JOIN PendingCartItems ON products.id = PendingCartItems.product_id
WHERE PendingCartItems.pending_cart_id = 18
GROUP BY PendingCartItems.pending_cart_id

You'll need to join the two tables:-
select
sum(p.price)
from Products p
inner join PendingCartItems pci on p.id= pci.product_id
where pci.pending_cart_id = 18

Related

I want to do inner join of some colums but still show the other colums if thats possible

basically i have a quest to do where i have to get all the details (product_purchase,price_history ,product colums that are name,type,id and price)from just searching for a product id.i basically did
select price_history.product_id, product.id, product_purchase.product_id from ((price_history
inner join product on price_history.product_id = product.id)
inner join product_purchase on price_history.product_id = product_purchase.product_id);
right now it just gives me the product id from product_purchase price_history and the id from product and i wanted it to show all the other colums from the 3 tables and want to have an option where i can do an input of the id something like
where product.id= %s
Try this.
SELECT *
FROM price_history
INNER JOIN product
ON price_history.product_id = product.id
INNER JOIN product_purchase
ON price_history.product_id = product_purchase.product_id
WHERE product_id = %substitutedParameter%
But, as you will see, SELECT * gives you some redundant columns. It's good practice to name the columns you want in your SELECT.... something like this, I guess.
SELECT price_history.product_id,
product.description,
product_purchase.vendor
...

How to apply two where condition one inside subquery and the other out of subquery?

Find the customer that spend less than 3$ on individual film rentals, but has spent a total higher than 15?
The query that I wrote is given below
SELECT CustomerID,Customer.CustomerFirstName,Customer.CustomerSurname,Total FROM (SELECT DISTINCT Customer.CustomerID,Customer.CustomerFirstName,Customer.CustomerSurname,sum(([Rental].[Quantity])*([Film].[FilmPrice])) AS Total
FROM Film RIGHT JOIN (Customer INNER JOIN Rental ON Customer.CustomerID = Rental.CustomerIDFk) ON Film.FilmID = Rental.FlimIDFk
GROUP BY Customer.CustomerID,Customer.CustomerFirstName,Customer.CustomerSurname) T WHERE Total>15;
Now how can I apply the second condition which is FilmPrice<3
Please help me out.
This is the ERD
Thanks
Simply add another where clause inside the subquery, after your join on but before the group by for WHERE FilmPrice<3
You want to find the customers where the maximum price of a film they have rented is less than 3 and the total price of all the films they have rented is greater than 15.
Something like this:
SELECT CustomerID,
CustomerFirstName,
CustomerSurname
FROM Customer
WHERE CustomerId IN (
SELECT r.CustomerIDFk
FROM Rental r
INNER JOIN Film f
ON ( f.FilmId = e.FilmIdFk )
GROUP BY r.CustomerIdFk
HAVING MAX(f.FilmPrice) < 3
AND SUM(f.FilmPrice * r.Quantity)>15
)

Need help for writing query for a marketplace in postgres

I have database for a marketplace which looks like this:
I have different suppliers selling the same product at different price points, also some products are more popular than others in a given location. For example we have product A and product B, and product A is more popular that product B based on how many has already been sold in that location, and for product A we have 3 suppliers. I want my query to show product A from the cheapest seller, then product B from the cheapest seller. I can achieve that with this code:
WITH tem_1 AS (SELECT product_id, MIN(price) AS price FROM product_supplier GROUP BY product_id) ,
tem_2 AS (SELECT product_id, SUM(quantity) AS n_orders FROM orders Group by product_id)
SELECT products.product_id, suppliers.supplier_id, products.name, tem_1.price,
COALESCE(tem_2.n_orders,0) AS quant FROM products
INNER JOIN product_supplier ON product_supplier.product_id = products.product_id
INNER JOIN suppliers ON suppliers.supplier_id = product_supplier.supplier_id
INNER JOIN product_code ON product_code.code_id = products.code_id
INNER JOIN product_crop ON product_crop.product_id = products.product_id
INNER JOIN crops ON crops.crops_id = product_crop.crop_id
INNER JOIN product_tags ON product_tags.product_id = products.product_id
INNER JOIN tags ON tags.tag_id = product_tags.tag_id
INNER JOIN tem_1 ON tem_1.price = product_supplier.price AND tem_1.product_id = products.product_id
LEFT JOIN tem_2 ON tem_2.product_id = products.product_id
WHERE crops.crops_id = 1 AND product_supplier.quantity >= 3 AND tags.tag = 'علف کش'
ORDER BY quant DESC
LIMIT 10;
The problem is, if i have two different suppliers from different locations, selling the same product with the same price, the results show that product twice, but i only want the results from the closest supplier to the user, in this case product 101 from supplier 3 and not the supplier 1.
I think i have to use MIN(ST_Distance("geopoint from user", "geopoint from suppliers")) and LATERAL to have a distance filed, but because i'm using aggregate functions, in order to do a GROUP BY to remove the duplicate results, i have to add all the fields product_id, supplier_id, name, price, ... to the GROUP BY and that won't result in removing the duplicates.
Any suggestion on how to achieve that?
Your query is rather hard to follow. But, distinct on solves your problem. I'm not 100% sure what you want to be distinct, but something like this:
select distinct on (product_id, price) . . .
from . . .
where . . .
order by product_id, price, ST_Distance("geopoint from user", "geopoint from suppliers");
This returns one row per product and price, based on the smallest distance.
If you want the data ordered in a different way, then use this as a subquery or CTE and order by again in the outer query.

Get the total sum of 2 multiplied columns SQL

I have these 3 tables:
Bill:
idBill
Products:
idProduct
price
BillProducts (that connects the tables above):
idBill
idProduct
quantity
Now let's say I wish to get the total price of a certain bill identified by its ID
I would need to multiply the columns of Products.Price by BillProducts.quantity, get its result and sum all the others products in that idBill
Can you guys help me writing that query?
SELECT SUM(QUANTxPRICE) AS SUMED, IDBILL FROM (
SELECT (A.QUANTITY * B.PRICE) AS QUANTxPRICE,a.IDBILL
FROM BILLPRODUCTS AS A
JOIN PRODUCTS AS B ON
A.IDPRODUCT = B.IDPRODUCT
JOIN BILL AS C
ON A.IDBILL = C.IDBILL
) AS X
GROUP BY IDBILL
You would do:
select sum(p.price * bp.product)
from billproducts bp join
products p
on bp.idproduct = p.idproduct
where idbill = <idbill>;
You can get this for all bills using group by:
select idbill, sum(p.price * bp.product)
from billproducts bp join
products p
on bp.idproduct = p.idproduct
group by idbill;
Notes:
You do not need to join the bills table. All the information you need is in the other two tables.
You do not need a subquery.
When you define table aliases, they should be abbreviations for the table names, so the query is easier to follow.

Basic SQL Joining Tables

Having a bit of trouble with a basic SQL problem.
The question is that I have to find the salespersons first and last name, then their Social Insurance Number, the product description, the product price, and quantity sold where the total quantity sold is greater than 5.
I'll attach the database information below as a photo.
Product quantity sold greater than 5
SELECT ProductId
FROM ProductsSales
HAVING SUM(QuantitySold) > 5
Use that to get the rest:
SELECT s.FirstName, s.LastName, s.SIN, p.ProductDescription, ps.UnitSalesPrice, ps.QuantitySold
FROM ProductsSales ps
LEFT JOIN Products p on p.ProductID = ps.ProductID
LEFT JOIN Salesmen s on s.SalesmaneID = ps.SellerID
WHERE ps.ProductID IN
(
SELECT ProductId
FROM ProductsSales
GROUP BY ProductId
HAVING SUM(QuantitySold) > 5
)
SELECT a.FirstName, a.LastName, a.SIN, c.ProductDescription, b.UnitSalesPrice, b.QuantitySold
FROM Salesmen a
LEFT JOIN ProductsSales b
ON a.SalesmanId = b.SellerId
LEFT JOIN Products c
ON b.ProductId = c.ProductId
WHERE b.QuantitySold > 5
Select a.FirstName, a.LastName, a.SIN From Salesmen as a,
c.ProductDescriptio, c.Price, b.sum(QunatitySold)
inner join ProductSales as b on a.Salesmanid = b.sellerid
inner join Products as c on c.ProductId = b.ProductId
having b.sum(QunatitySold)> 5
group by a.FirstName, b.ProductDescription
Brad,
Welcome to SQL. Joining for me was a terrifying experience when I first started but its really easy. The general concept is this:
Pick a Join
If you want to see all records that would be common between the two table, you would use and JOIN. If you wanted to combine the two tables but still show all records you use LEFT JOIN
The basic syntax is
SELECT fieldnames FROM tablename alias
JOIN othertable alias ON firstalias.field = secondalias.field
--Example
SELECT animal, food, idtag from animals a
JOIN food f on a.animalid = f.animalid
This assumes you have a common field animalid in both the animals table and the food table. you should also ideally preface the field names with the alias to make it easier to understand like this: a.animal, f.food
And you keep going until you have joined all the tables you need.
Make sure you only request field names you want
Hope that helps