MYSQL - SUM of a column based on common value in other column - mysql

I'm stuck on crafting a MySQL query to solve a problem. I'm trying to iterate through a list of "sales" where I'm trying to sort the Customer IDs listed by their total accumulated spend.
|Customer ID| Purchase price|
10 |1000
10 |1010
20 |2111
42 |9954
10 |9871
42 |6121
How would I iterate through the table where I sum up purchase price where the customer ID is the same?
Expecting a result like:
Customer ID|Purchase Total
10 |11881
20 |2111
42 |16075
I got to: select Customer ID, sum(PurchasePrice) as PurchaseTotal from sales where CustomerID=(select distinct(CustomerID) from sales) order by PurchaseTotal asc;
But it's not working because it doesn't iterate through the CustomerIDs, it just wants the single result value...

You need to GROUP BY your customer id:
SELECT CustomerID, SUM(PurchasePrice) AS PurchaseTotal
FROM sales
GROUP BY CustomerID;

Select CustomerID, sum(PurchasePrice) as PurchaseTotal FROM sales GROUP BY CustomerID ORDER BY PurchaseTotal ASC;

Just by having a little Google search, I managed to find a page doing exactly what you're doing (I think). I have tailored the query below to fit your circumstance.
SELECT CustomerID, SUM(PurchasePrice) AS PurchaseTotal
FROM sales
GROUP BY CustomerID
ORDER BY PurchaseTotal ASC
Link to Page with Tutorial on SQL Groups

Related

How to solve this MySQL COUNT query?

Three table are given:
customer(cust_id, name, address, sales_id)
orders(order_id, cust_id,date, sales_id)
salesman(sales_id,commision)
and you have to write an MySQL query to "count the salesman by their order_id and date". Is the question is correct? if yes, how can I solve this.
The question is not clear, but the codes below will give you an idea of how to get aggregated results and you can play around / adjust based on your needs
select
date,
sales_id,
count(order_id) as total_orders_per_date_and_sales_id
from orders
group by 1,2
if you need the total salesman per date then you can do this:
select
date,
count(sales_id) as total_sales_man_per_date
from orders
group by 1
if one order has multiple sales owners, then you can find total salesman per order id
select
orders_id,
count(salesman) as total_sales_man_involved_per_order
from orders
group by 1
if you need total commission per salesman per date:
select
orders.date,
orders.sales_id,
sum(salesman.comission) as total_comssion_per_salesman_per_date
from orders
left join salesman
on orders.sales_id = salesman.sales_id
group by 1,2
total number of distinct salesman
select
count(distinct sales_id) as total_unique_salesman
from salesman

Get best-selling product based on year

I want to write a sql query to get best product of each year from a table . I have grouped the product-id and sum the qty to get the total number of products per id.
I converted the datetime function into year to get the year but output is wrong..
Anyone can help me with this?
SELECT Year(ModifiedDate), ProductID, SUM(OrderQty) AS TotalQuantity
from Sales.SalesOrderDetail
GROUP BY ProductID, year(ModifiedDate)
having count(*) > 3000
ORDER BY SUM(OrderQty) DESC
From your comment:
query is working fine if the set having condition to 2000. but if i
set it to 3000 it return nothing. if i use this "having count() >
2000" so i get two records. first of 2013 which return total quantity
3913 and record of 2014 with total quantity 2902. but when i change
condition to this "having count() > 3000 " it return nothing. but it
should return the 2013 record
You select the sum of OrderQty, yet you filter on the count and expect it to be the same. Count is the number of records, it doesn't care about the actual values in the records.
When you filter with
having sum(OrderQty) > 3000
you will only get the 2013 record.
We can do it in two-part.
I) create a temporary table for year-wise, id wise sum of qty.
create table tempSaleOrderDetail as select year(ModifiedDate) year,sum(OrderQty) orderqty, ProductID from Sales.SalesOrderDetail group by year(ModifiedDate), productId order by 1 desc,2 desc;
II) Fetch the data.
select A.* from tempSaleOrderDetail A inner join (select year ,max(orderqty) orderqty from tempSaleOrderDetail group by year) B on A.year=B.year and A.orderqty=B.orderqty ;
If any year has more than one Id's performance is same so this query will give both results.

MySQL - Average number of particular product sold on date

I need to write SQL query for "average number of particular product sold by date. On each day is sold min one product".
SELECT AVG (COUNT (PID))
FROM SOLD
GROUP BY DATE, PID;
P.S. PID means Product ID.
Is this query okay?
Should this give right answer?
Consider Using distinct count of date columns
SELECT PID,
COUNT(PID)/COUNT(distinct date_) as "Avg.Product Sold By Days"
FROM SOLD
GROUP BY PID;
You can try this sql query below. Basically, it will return the average number of 'SALES' for each product you have. It will group by each distinct product ID. Please provide us the data structure your of table and etc.
SELECT product_ID, trans_date
Sum(sales_of_product) / COUNT(DISTINCT sold_transaction) AS 'avg'
FROM SOLD
GROUP BY product_ID

Finding average highest salary

Write a query to find the highest average sales among all the salespersons using the given table.
Table: Sales
Field Type
InvoiceNo Integer
SalesPerson Text
TotalSale Integer
Sample
InvoiceNo SalesPerson TotalSale
1 Acheson 50
2 Bryant 25
3 Bennett 250
4 Acheson 50
5 Bryant 100
6 Bennett 250
Sample output
max(totalsale)
250.0000
I tried using: SELECT MAX(TotalSale) FROM Sales. My output for sample test case was 250 but it was given wrong answer verdict in an online judge.
Also, when I changed the query to : SELECT MAX(TotalSale*1.0000) FROM Sales,I got correct answer for sample test case but still wrong answer for other test cases.
What is meant by average here? What should be the query?
Also, this isn't from any on-going competition. It is from a practice test which you can attempt here: https://www.hackerearth.com/challenge/test/kredx-data-analyst-test/
1.First you have to calculate the average TotalSale for each SalesPerson using the AVG function.
SELECT SalesPerson, AVG(TotalSale) AS 'TotalSale'
FROM Sales
GROUP BY SalesPerson
2.Find out the max value from the table generated by the above query.
SELECT MAX(avgSales.TotalSale)
FROM (SELECT AVG(TotalSale) AS 'TotalSale' FROM Sales GROUP BY SalesPerson) AS avgSales
SELECT avg(TotalSale) as MaxTotal
FROM Sales
GROUP BY Salesperson
ORDER BY MaxTotal desc
LIMIT 1
Output:
MaxtTotal
250.0000
The average sale would use the avg() function:
select salesperson, avg(totalsale) as avg_totalsale
from sales
group by salesperson;
The maximum of the average can be obtained using order by and limit:
select avg(totalsale) as avg_totalsale
from sales
group by salesperson
order by avg_totalsale desc
limit 1;
Here is another way to answer this:
select avg(TotalSale)
from Sales
group by SalesPerson
order by totalSale desc limit 1;
output:
avg(TotalSale)
250.0000
Minor change to #gordon-linoff 's answer to pass the sample test case.
select CAST(avg(totalsale) AS DECIMAL(16,4)) as avg_totalsale
from sales
group by salesperson
order by avg_totalsale desc
limit 1;
CAST(avg(totalsale) AS DECIMAL(16,4))
The above part will restrict the zero's in decimal place up to 4. Convert 250.00000000 to 250.0000
SELECT max(avgsale.TotalSale)
FROM (Select Cast(Round(Avg(TotalSale),2) as dec(10,4)) 'TotalSale' from Sales
GROUP BY salesPerson) avgsale

How to get the best 10 (top 10) in a query that is also ordered by another field first?

For example I would like to get only the top 10 customer by seller. So it will look like this (without the top 10):
Select seller, customer, sells from table order by seller asc, sells desc
But this will give me all the values. I would only like to have the first 10 customers for each seller.
Is this even possible in ms-access 2003? If yes, please give me a hint,
thanks ;)
On the lines of:
SELECT seller,
customer,
sells
FROM table a
WHERE customerid IN (SELECT TOP 10 customerid
FROM table b
WHERE b.sellerid = a.sellerid
ORDER BY sells DESC)
ORDER BY seller ASC,
sells DESC
Note that MS Access returns matches, so you may get more than 10 returns. If an exact 10 is required, you can order by a unique ID as well as sells.