find Sum of Sub-Query - mysql

Query need to find a client named Yossi Cohen, who purchased a number of items and the amount billed(sum) of purchase
For example: Yossi Cohen bought three items costing 40 shekels and we want to know the amount of the order.
example:
namecustomer namemodel quantity sum
Yossi Cohen iphone6 3 120
I try to write this:(not working)
SELECT nameCustomer,
(SELECT idCustomer,nameCustomer,nameModel,idOrders,Quantity,
SUM(price*Quantity)AS OrderTotal
FROM Customers,OrdersItems,Products GROUP BY idOrders)
FROM Customer
where Customer = 'Yossi Cohen';

This should do the work:
SELECT idCustomer,nameCustomer,nameModel,idOrders,Quantity
From Customer
Where sum=price*Quantity
AND Customer = 'Yossi Cohen';

Related

Total amount of sales done for each product using SQL

Here is the structure of 1st Table called Product.
PRODID PDESC PRICE CATEGORY DISCOUNT
101 BALL 10 SPORTS 5
102 SHIRT 20 APPAREL 10
Here is the structure of 2nd table called SaleDetail.
SALEID PRODID QUANTITY
1001 101 5
1001 101 2
1002 102 10
1002 102 5
I am trying to get total sales amount for each product by joining 2 tables. Here is the SQL i tried but its not giving correct result.
select a.prodid,
(sum((price - discount))),
sum(quantity),
(sum((price - discount))) * sum(quantity)
from product a
join saledetail b on a.prodid = b.prodid
group by a.prodid
2nd column of the query is giving incorrect final price. Please help me correct this SQL.
Please find an indicative answer to your question in the fiddle.
A problem stems from the aggregation of the difference of price. In case that the same product has two different prices, then these prices would be aggregated to one.
Moreover, you multiple the sums of the prices and quantities, while you need to perform the calculation on every sample. Look at the answer by #DanteTheSmith.
You might consider to use the SaleDetail table on the left side of your query.
SELECT SD.PRODID,
P.Price-P.Discount AS Final_Price,
SUM(SD.QUANTITY) AS Amount_Sold,
SUM((P.Price-P.Discount)*SD.QUANTITY) AS Sales_Amount
FROM SaleDetail AS SD
JOIN Product AS P
ON SD.PRODID = P.PRODID
GROUP BY SD.PRODID, P.Price-P.Discount
It would help if you built the example in SQL fiddle or gave the creates for the tables, but if I have to guess your problem is:
(sum((price - discount))) * sum(quantity)
needs to be:
sum((price - discount) * quantity)
(price - discount) * quantity is the function you wanna apply PER ROW of the joined table then you wanna add all those up with SUM() when grouping by prodid.
Furthermore, you can notice that (price - discount) needs to be done ONLY ONCE PER ROW so a quicker version would be to do:
(price-discount) * sum(quantity)
That would give you the total money earned for that product across all the sales you made, and I am guessing this is what you want?
I just notice you have a problem with 2nd column, dunno if that has been in question all along:
(sum((price - discount)))
Why are you summing? Do you want the money earned per product per unit of the product? Well guess what, your price is the same all the time, same as your discount so you can simply go with:
(price-discount) as PPP
NOTE: This assumes the discount is numerical (not percentage) and is applicable to all your sales, also the price is forever the same all which is not real life like.

How to join tables correctly. 0 rows returned is not correct

Everything looks in order for the code to run, but the code isn't showing any rows. So, i must be doing something wrong. I can't figure out where the problem is. The problem from my instructor is:
Use the AP database
Vendor name from the vendor table
Vendor Contact First Name and Vendor Contact Last Name from the vendor table but I need them concatenated together with a space between the names
Invoice Date from the invoice table
Only the day of from the Invoice Date
Invoice Number from the invoice table
The third and fourth characters from the Invoice Number
Line Item Amount from the invoice line items table
Calculate the commission which is the Line Item Amount * 15% and make it ONLY two decimals
The FROM is the Vendors table do JOINS on the others
The WHERE is where the Line Item Amount is greater than $2000 and the Invoice Date is between July 1, 2014 and July 31st, 2014 and I only want the ones that have either a 9 or a 2 in the Invoice Number
Sort by Invoice Date
// This is the only information he's given me for this assignment. ^
I've tried to join different columns together in different orders/joining tables in different orders.
select vendor_name as vendor, concat(first_name, ' ', last_name) as Contact,
DAY(invoice_date) as ofday, invoice_date,
SUBSTRING(invoice_number, 3,2) as thirdFourth,
line_item_amount,round(line_item_amount*.15, 2) as Commission
from vendors v
JOIN vendor_contacts vc
ON v.vendor_id = vc.vendor_id
JOIN INVOICES INV
ON VC.VENDOR_ID = INV.VENDOR_ID
JOIN invoice_line_items ILI
ON INV.invoice_id = ILI.invoice_id
where line_item_amount > 2000
and invoice_date between '2014-7-1' and '2014-7-31'
and (invoice_number =9 OR invoice_number =2)
expected results :
https://imgur.com/E81ix3o
At the moment you are asking specifically for invoice_number 9 or 2. You don't have an invoice_number of 9 or 2 If you want invoice_numbers with 9 or 2 in you will need
invoice_number like '%9%' or invoice_number like '%2%'

mySQL: Given 2 column data, find 3rd column and then AVG() 3rd column based on 2nd column

I've 3 columns, staffName, dateOfIncident, incidentNo. I'm looking for 'total incidents' which will be the total number of incidents from a certain staff for a particular year, which I get from dateOfIncident. Now I must find the average of the number of 'total incidents', finally providing the headings:
staffName | avgIncidents
What I have so far is:
SELECT l.staffName, l.dateOfIncident, COUNT(l.incidentNo) AS avgIncidents
FROM incidentsR l
Which displays:
staffName | dateOfIncident | avgIncidents
.... | ..... | ....
Though this obviously supplies 3 columns output, and so far I'm only able to count the total amount of incidents, which I then need to use to calculate the avg.
What I need help with is how to take information from the first 2 columns of name and date to find the 'total incidents' for that specific person for that year. And then for each staffName calculate the average of the number of 'total incidents' for the years we have data on the staff.
Your query would be:
SELECT l.staffName, year(l.dateOfIncident) as year,
COUNT(*) as incidentsPerYear
FROM incidentsR l
GROUP BY l.staffName, year(l.dateOfIncident);
To get the average per year for the staff, you could use a subquery. Or do the calculation directly:
SELECT l.staffName,,
COUNT(*) / COUNT(DISTINCT year(l.dateOfIncident))as avgIncidentsPerYear
FROM incidentsR l
GROUP BY l.staffName;

Sum on multi-joined tables

I have 4 tables
customers
sales
sale_items
stock_items
I want to list all my customers. For each customer I want the total amount purchased - a field that I want the sql query to create (xxx as totalSales)
I tried selecting customers as the primary table and joining other tables on it. I tried selecting sales as the primary table and also the sale_items. I kind of got the correct sum calculation but it will show me the first customer first.
This is what my tables look like:
*TABLE customers*
id
customer_name
email
*TABLE sales*
id
customer_id
transaction_date
*TABLE sale_items*
id
sale_id
stock_item_id
*TABLE stock_items*
id
item_name
price
I want to
Create a list of all customers, sorted by the customer with the most sales (in value) first. Not the count of the sales, but the total amount (sales value) of the sales
Display the items purchased per customer under the customer name. This would not be per order, but for all sales. So if a tin of coffee was purchased by customer X, over a count of 4 orders each, the tin of coffee would display 4 times. Though if possible I'd like the items listed a-z.
I have inner joined the tables on each other, so I would get a list of all transactions. I've tried SELECT * FROM customers, tried FROM sales, tried from sale_items. I've tried GROUP_BY customer_id, but then I would get incorrect counts.
I want to display the data as such.
CUSTOMER ITEMS TOTAL VALUE
John Doe Coffee
Milk
Tea
Milk
Bread
Coffee 500
Jane Doe Coffee
Milk
Coke 350
Denver Doe Coffee
Milk
Bread
Bread 125
I don't want to use PHP and make a query for every single "thing". I am trying to run one or two queries.
I don't think you're going to be able to quite get them in separate rows like you're showing (unless you look into the ROLLUP function), but that's probably not a requirement for you.
I think you should use GROUP_CONCAT which is an aggregation function sort of like SUM but it creates a comma separated list out of all of the values:
SELECT
*
SUM(sale_amount) as total_sales,
GROUP_CONCAT(item_name) as item_names
FROM customers c
JOIN sales s USING (customer_id)
JOIN sale_items si USING (sale_id)
JOIN stock_items sit USING (stock_item_id)
GROUP BY customer_id
What you should see as a sample row is:
Denver Doe Coffee,Milk,Bread,Bread 125
(I had to make up some column names, like sale_amount, but you must have those in there I'm sure. You'll have to make some adjustments in those names and maybe in how I did the joins as well, but this should work with some changes if I'm understanding your needs).

multiply two columns from two different tables and group them together

I have two tables in MySQL which are sale and material details.
I want to calculate the profit I made by selling items which is
profit = (total) -(qty* landedcost)
Here is the structure of the two tables:
This is the query
SELECT sale.name ,sale.total-(sale.qty * materialdetails.landingcost) AS
result
FROM sale JOIN materialdetails
on sale.id = materialdetails.id
GROUP BY sale.name,result;
the result i get :
query result
I want something like this
name result
A4 5000
Computer 40000
Flash memory 1000
Headphone 22000
Mobile 35000
Any idea please?
You should sum the result and group by sale.name only, something like this:
SELECT sale.name ,sum(sale.total-(sale.qty * materialdetails.landingcost)) AS
result
FROM sale JOIN materialdetails
on sale.id = materialdetails.id
GROUP BY sale.name;
Explanation: if you group by two fields GROUP BY sale.name,result you will get one line for all records that have the same sale.name and result, so for instance
name result
Computer 10000
Computer 25000
are two different lines and they are not grouped together as one.