Getting the Maximum Average price based on Product Name - mysql

I have a Products table with three headers namely ProductID, ProductName and Price.I need to find the name of the product which is having maximum average price. There are multiple products and they are duplicate as well for different product ID and i need their average price.
Sample Data looks like below :
ProductID ProductName Price
1 A 18
2 A 19
3 B 10
4 C 22
5 D 21.35
6 C 25
7 A 30
8 B 40
9 E 97
10 A 31
Query that i have written is as below:
SELECT ProductName
FROM Products
group by ProductName
order by avg(Price) desc
limit 1;
But i was informed that it is not a generic solution. Can anyone please inform, what is wrong in this query.

The only problem with your query is the case where there are more than 1 products with average price equal to the maximum average price, because it returns only 1 row.
To cover this case you need to group again and use your query in the HAVING clause :
select productname
from products
group by productname
having avg(price) = (
select avg(price)
from products
group by productname
order by avg(price) desc
limit 1
);
See the demo.

Related

Generating table with SUM columns based on different conditions

I am fairly new to SQL and I am struggling with generating a table with multiple aggregates based on certain filters.
My temporary able has 3 columns where an individual is unique by Category ID AND Customer ID (i.e. there can be multiple identical Customer IDs across categories).
Category ID
Customer ID
Number of Purchases
X
A
4
X
B
10
X
C
2
Y
A
2
Y
E
6
Z
A
10
Z
C
5
Z
D
7
The output table I am looking for is basically 4 columns: grouped by category ID identifying total number of customers who have at least 3 purchases, customers who have at least 5 purchases as well as total purchases across all customers within that category. The output table would look like this:
Category_ID
Total_Customers_3
Total_Customers_5
Total_Purchases
X
2
1
16
Y
1
1
8
Z
3
3
22
When I input the following code, I get the correct total purchases column per category but the total number of customers who had at least 3 purchases per category is incorrect as the aggregates are identical across all categories.
My code:
SELECT table.categoryID AS Category_ID
(SELECT COUNT (table.customerID)
FROM table
WHERE table.purchases >=3) AS Total_Customers_3,
(SELECT COUNT (table.customerID)
FROM table
WHERE table.purchases >=5) AS Total_Customers_5,
SUM (table.purchases) AS Total_Purchases,
FROM table
GROUP BY Category_ID, Total_Customers_3, Total_Customers_5,
(P.S When I try to just GROUP BY Category_ID, I get an ERROR that syntax is incorrect because I have sub-queries in my SELECT statement.
The incorrect table (i.e. same number of total customers meeting the condition across all categories) I get looks like:
Category_ID
Total_Customers_3
Total_Customers_5
Total_Purchases
X
2
1
16
Y
2
1
8
Z
2
1
22
Update: I should have included this in the original question but I am actually looking to generate 2 columns in the same about total number of customers based on 2 conditions - one for customers with at least 3 purchases and another column for customers with at least 5 customers.
Aggregate by category, and the use conditional aggregation to get the counts and totals.
SELECT
Category_ID,
SUM(purchases >= 3) Total_Customers_3,
SUM(CASE WHEN purchases >= 3 THEN purchases ELSE 0 END) AS Num_Purchases_3,
SUM(purchases >= 5) Total_Customers_5,
SUM(CASE WHEN purchases >= 5 THEN purchases ELSE 0 END) AS Num_Purchases_5
FROM yourTable
GROUP BY Category_ID;
Demo

SQL task if the product has no sales in the given month, then display 0 in this month

I have to build and SQL query which must do these things:
select all products from table "products" - satisfied
SUM all sales and forecast to the next 3 months - satisfied
check if the product has no one sale, then write "0" -> here is the problem, because I don't know how to do that..
My SQL query is here..
select product.name,
(select sum(amount)
from forecast
where forecast.product_id = product.id),
sum(sale.amount)
from product join
 sale
  on sale.product_id = product.id
where sale.outlook > -4
group by product.id
Here is the products table:
id name
1 milk
2 roll
3 ham
Table sale (same structure like forecast):
product_id outlook amount
1 -1 9
1 -2 13
1 -3 14
2 -1 88
2 -3 61
3 -1 33
3 -4 16
You can use left join to bring in the rows and coalesce() to get the 0 instead of NULL:
select p.name,
(select sum(f.amount)
from forecast f
where v.product_id = p.id),
coalesce(sum(s.amount), 0)
from product p left join
sale s
on sale.product_id = product.id and
sale.outlook > -4
group by p.id
Understand the requirement to be, show the sales per product and if no sale for a product show "0". Tables are named Products and Sale.
For this, "with" statements are useful and help understanding too:
With SalesSummary as
(
select product_id, sum(amount) as ProductSales
from Sale
Group by product_id
)
select a.ProductID, ISNULL(b.ProductSales,0) as Sales
from products a left join SalesSummary b on a.product_id=b.product_id

How to show all MIN of SUM(column) that has the same min value?

I've been trying to get MIN of SUM of a column by doing subqueries, however in a case where I have two same SUM values, my query only returns me one of them. Is there a way to get all of them to be shown?
So for example this table is called quantity,
date product_id quantity_start quantity_end
1/1/2020 1 10 5
1/1/2020 2 10 5
1/1/2020 3 12 1
2/2/2020 1 10 5
2/2/2020 2 11 6
2/2/2020 3 14 1
my query would be
SELECT product_id, MIN(Total) as Minimum
FROM (SELECT product_id, SUM(quantity_start - quantity_end) as Total
FROM quantity
GROUP BY product_id)T
But this will return me only one min value while there are two since both product 1 and 2 will have total of 10 from my subquery. Is there a way to write it such that it shows me both ?
Thanks!
You are correctly grouping by your sub query, but the outer query also needs a group by so:
SELECT product_id, MIN(Total) as Minimum
FROM (SELECT product_id, SUM(quantity_start - quantity_end) as Total
FROM quantity
GROUP BY product_id)T
GROUP BY product_id;
See it working here: http://sqlfiddle.com/#!9/97d7724/1

MySql Query to sum the rows and get the max value

I have a table product with sample data as below
product 1 2 2 3 1
Quantity 10 15 20 10 5
I need to findout which product has highest quantity after summing up all the available quantity for all the products
Example: Here answer would be 15+20 = 35 is greatest so product 2 has more quantity
please help with query
select product, sum(quantity) as sum_quantity
from products
group by product
order by sum_quantity desc
limit 1

DISTINCTROW by id

SELECT
DISTINCTROW ProductsId AS pid,( SELECT SUM(QuantityByID) WHERE ProductsId=pid )
FROM
cartitem
I want to get this result
ProductId Quantity
7 7
13 2
14 2
9 1
It's hard to help without a question but I think you want a GROUP BY:
SELECT ProductsId as pid, SUM(QuantityByID)
FROM products
GROUP BY ProductsId
This will give the sum of quantity for each product id.