Sum on multi-joined tables - mysql

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).

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.

find Sum of Sub-Query

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';

Query: COUNT in Access To Only Count Unique Values

I have a table like so:
Customer Purchase Date Product
Frank 7/28/2015 Hammer
Bob 7/29/2015 Shovel
Bob 7/29/2015 Pickaxe
Bill 7/30/2015 Pliers
The Purchase Date field records a new entry for every purchase. So, if in one visit a customer purchases four items, my database creates four entries each with the same date.
I'm trying to write a query that displays the numbers of visits for each customer. Output like so:
Frank 1
Bob 1
Bill 1
But when I use the COUNT function on the date in my query, it returns:
Frank 1
Bob 2
Bill 1
I want my query to only count unique dates, but the COUNT function doesn't work. Everywhere I read, it also says that the SQL COUNT (Distinct) doesn't work in Access. Access help says that if I set the Query Properties to Unique Values "Yes", it should only return unique values, but it doesn't work. I tried Unique Record "Yes" also, but that didn't work either.
Please help! Thanks!
Try this:
select Cust, count(cust) as CustomerCount
from (Select Distinct Table1.Customer as cust, Table1.PurchaseDate
from Table1)
group by cust

how to get average of rows that have a certain relationship

I have a bunch of data that is stored pertaining to county demographics in a database. I need to be able to access the average of data within in the state of a certain county.
For example, I need to be able to get the average of all counties who's state_id matches the state_id of the county with a county_id of 1. Essentially, if a county was in Virginia, I would need the average of all of the counties in Virginia. I'm having trouble setting up this query, and I was hoping that you guys could give me some help. Here's what I have written, but it only returns one row from the database because of it linking the county_id of the two tables together.
SELECT AVG(demographic_data.percent_white) as avg_percent_white
FROM demographic_data,counties, states
WHERE counties.county_id = demographic_data.county_id AND counties.state_id = states.state_id
Here's my basic database layout:
counties
------------------------
county_id | county_name
states
---------------------
state_id | state_name
demographic_data
-----------------------------------------
percent_white | percent_black | county_id
Your query is returning one row, because there's an aggregate and no GROUP BY. If you want an average of all counties within a state, we'd expect only one row.
To get a "statewide" average, of all counties within a state, here's one way to do it:
SELECT AVG(d.percent_white) AS avg_percent_white
FROM demographic_data d
JOIN counties a
ON a.county_id = d.county_id
JOIN counties o
ON o.state_id = a.state_id
WHERE o.county_id = 42
Note that there's no need to join to the state table. You just need all counties that have a matching state_id. The query above is using two references to the counties table. The reference aliased as "a" is for all the counties within a state, the reference aliased as "o" is to get the state_id for a particular county.
If you already had the state_id, you wouldn't need a second reference:
SELECT AVG(d.percent_white) AS avg_percent_white
FROM demographic_data d
JOIN counties a
ON a.county_id = d.county_id
WHERE a.state_id = 11
FOLLOWUP
Q What if I wanted to bring in another table.. Let's call it demographic_data_2 that was also linked via the county_id
A I made the assumption that the demographic_data table had one row per county_id. If the same holds true for the second table, then a simple JOIN operation.
JOIN demographic_data_2 c
ON c.county_id = d.county_id
With that table joined in, you could add an appropriate aggregate expression in the SELECT list (e.g. SUM, MIN, MAX, AVG).
The trouble spots are typically "missing" and "duplicate" data... when there isn't a row for every county_id in that second table, or there's more than one row for a particular county_id, that leads to rows not included in the aggregate, or getting double counted in the aggregate.
We note that the aggregate returned in the original query is an "average of averages". It's an average of the values for each county.
Consider:
bucket count_red count_blue count_total percent_red
------ --------- ---------- ----------- -----------
1 480 4 1000 48
2 60 1 200 30
Note that there's a difference between an "average of averages", and calculating an average using totals.
SELECT AVG(percent_red) AS avg_percent_red
, SUM(count_red)/SUM(count_total) AS tot_percent_red
avg_percent_red tot_percent_red
--------------- ---------------
39 45
Both values are valid, we just don't want to misinterpret or misrepresent either the value.

for loop functionality in mysql query

this is MYSQL query question
First, let say we have
[ALL_MENU]
name
-----
pasta
pizza
and people ordered
ordered
customer name status
john pasta delivered
kim pasta delivered
john pizza delivered
john pasta delivered
I want to go through the ordered table and find anyone who ordered all the menu
In this example, kim only ordered pasta so it should not be included
but john ordered both pasta and pizza, so it should be included on the result.
is There any type of query to do the 'For loop' ability?
thank you
(ps, right now I only allow to use
some basic function command from mysql
group by , create view, exists , all, not exist , unique such and such )
=========================================================================
Ok, From the answer
the count number of all menu thing is work when (customer,name) are the primary key
But what if i added the data column, and primary key as (customer,name,data)
customer name status date
john pasta delivered 3/4
kim pasta delivered 3/5
john pasta delivered 3/5
this is the new column i made
john ordered the only pasta with 2 different date,
but johns number of order count as 2.
so count method will not work for this
How do we fix this problem?
The functionality of a for loop is a cursor. (FYI, most DBMS have such a construct.)
But never use a cursor when a plain old query will do just fine.
Here is one possible solution:
SELECT customer
FROM ordered
GROUP BY customer
HAVING COUNT(DISTINCT name) = (SELECT COUNT(*) FROM all_menu)
(This assumes that all names in ordered are found in all_menus, e.g. there is foreign key. If not, you'll have to add JOIN all_menu ON ordered.name = all_menu.name in the FROM clause.)
EDIT: "Simple"(!) commands only:
SELECT customer
FROM ordered o1
WHERE NOT EXISTS (
SELECT * FROM all_menu
WHERE name NOT IN (SELECT name FROM ordered o2 WHERE o1.customer = o2.customer)
)