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
.
.
.
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.
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.
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.
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).
Use aggregated function with group by
select Manufacturer, count(productname) as countofProduct, avg(price) as avgprice
from tablename
group by Manufacturer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With