Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Distinct values in SQL, and using the distinct values in subquery

Tags:

sql

I am a bit new to SQL so I would appreciate some help with this.

Say I have a table that looks something like the following:

| Manufacturer | ProductName | Price |
|--------------|-------------|-------|
| A            | p1          | 1.00  |
| A            | p2          | 1.50  |
| B            | p3          | 1.00  |
| C            | p4          | 3.50  |
| C            | p5          | 3.50  |
| C            | p6          | 6.00  |

How do I loop through the table to return Each manufacturer, the number of products they sell and the average price of the products they sell. I can do each of these steps in a separate query but I am not sure how to put them all together in a loop.

For example, I know that "SELECT DISTINCT Manufacturer from table" will give me a list of all the manufacturers, but then how do I use each of these manufacturers to COUNT the products and AVG the prices? For Example, I would like to return:

Manufacturer   NumberofProducts        AveragePrice
A                  2                     1.25
.
.
.
like image 782
Alexander Avatar asked Feb 27 '19 07:02

Alexander


People also ask

Can we use distinct in subquery?

A DISTINCT clause and a GROUP BY without a corresponding HAVING clause have no meaning in IN/ALL/ANY/SOME/EXISTS subqueries. The reason is that IN/ALL/ANY/SOME/EXISTS only check if an outer row satisfies some condition with respect to all or any row in the subquery result.

Can we use multiple distinct in single query?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.

What is the purpose of distinct clause in SQL write a sample query using distinct clause?

SQL DISTINCT clause is used to remove the duplicates columns from the result set. The distinct keyword is used with select keyword in conjunction. It is helpful when we avoid duplicate values present in the specific columns/tables. The unique values are fetched when we use the distinct keyword.

Can you use distinct and ORDER BY together?

All titles are distinct. There is no way this query can be executed reasonably. Either DISTINCT doesn't work (because the added extended sort key column changes its semantics), or ORDER BY doesn't work (because after DISTINCT we can no longer access the extended sort key column).


1 Answers

Use aggregated function with group by

select Manufacturer, count(productname) as countofProduct, avg(price) as avgprice
from tablename
group by Manufacturer 
like image 142
Fahmi Avatar answered Nov 14 '22 22:11

Fahmi