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.
Related
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
)
I have been able to select this data, using these two sql queries
Query 1:
SELECT article_id, amount_required, amount_sold FROM products_articles,sales WHERE sales.product_id = products_articles.product_id
Query 2:
SELECT * FROM articles
What I want to do, is go through the first table (with amount sold and required) (it's fine that there are duplicate rows), and for each row in the table multiply the value of amount_sold and amount_required and then subtract that value from amount_in_stock where the ids match in the second table.
Example from the first row:
2 * 4 = 8, change amount_in_stock from 124 to 116.
And so on...
How can I do this using just sql?
UPDATE A
SET
A.amount_in_stock =(S.amountSold * S.amount_required)- A.amount_in_stock
FROM articles AS A
INNER JOIN
products_articles AS PA
ON PA.article_id= A.article_id
INNER JOIN Sales AS S
ON S.product_id=PA.product_id
Please try this:
Update articles a
inner join
(
SELECT article_id, sum(amount_required) amount_required, sum(amount_sold )amount_sold FROM products_articles inner join sales on sales.product_id = products_articles.product_id
group by article_id
)b on a.article_id=b.article_id
set a.amount_in_stock=a.amount_in_stock-(amount_required*amount_sold )
Since there could be multiple rows in product_articles and amount_sold I have used group by to sum the amounts.
For SQLite please try this:
Update articles
set amount_in_stock=(SELECT sum(amount_required) * sum(amount_sold ) FROM products_articles inner join sales on sales.product_id = products_articles.product_id
where products_articles.article_id=articles.article_id
group by article_id
)
where exists (SELECT * FROM products_articles inner join sales on sales.product_id = products_articles.product_id where products_articles.article_id=articles.article_id
)
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
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
I have to 2 queries below which calculate to correct value:
Select Finances.CustomerID,
sum(Finances.Total)Total
from Finances
group by Finances.CustomerID
order by Finances.CustomerID
Select Invoices.CustomerID,
sum(Invoices.InvoiceValue)InvoiceValue
from Invoices
group by Invoices.CustomerID
order by Invoices.CustomerID
within the Finances table a customer can owe money from multiple orders, so for this example lets say the customer has to pay £100+ £400 + £500, which totals to £1000.
the customer then receives the 1st invoice for £100, and pays this..
so the 2nd query would now display £100.... from these 2 values I then want to calculate a 3rd column which deducts the £100 away from the £1000 equalling £900 (the amount left to pay)
the is my table structure:
there are a lot more tables associated however this is where I am the data from with the select statements :)
how would i write the sql statement to do this all together or is it not possible? ideally i would like the to be used within a INSERT -> SELECT -> WHERE NOT EXISTS Statement or alternatively populated in a view. thanks for the help
SAMPLE DATA:
CREATE VIEW CustomerFinances AS
;WITH FinancesCTE AS
(
Select Finances.CustomerID,
sum(Finances.Total)Total
from Finances
group by Finances.CustomerID
),InvoicesCTE AS
(
Select Invoices.CustomerID,
sum(Invoices.InvoiceValue)InvoiceValue
from Invoices
group by Invoices.CustomerID
)
SELECT C.*,
F.Total AS FinanceTotal,
I.InvoiceValue
FROM Customers C
LEFT JOIN FinancesCTE F
ON C.CustomerID = F.CustomerID
LEFT JOIN InvoicesCTE I
ON C.CustomerID = I.CustomerID
GO
Try this,
CREATE VIEW CustomerFinanceDetails AS
(
select c.*,isnull(FinanceTotal,0) as FinanceTotal,isnull(InvoiceTotal,0) as InvoiceTotal
from
(select * from Customers) c
left outer join
(select CustomerID,isnull(SUM(Total),0) as FinanceTotal from Finances group by CustomerID) f on c.CustumerID=f.CustomerID
left outer join
(select CustomerID,isnull(SUM(InvoiceValue),0) as InvoiceTotal from Invoices group by CustomerID) i on c.CustumerID= i.CustomerID
)