SQL Exercises: Compute the average price for unique companies
SQL Aggregate Functions: Exercise-23 with Solution
From the following table, write a SQL query to compute the average price for unique companies. Return average price and company id.
Sample table: item_mast
PRO_ID PRO_NAME PRO_PRICE PRO_COM ------- ------------------------- -------------- ---------- 101 Mother Board 3200.00 15 102 Key Board 450.00 16 103 ZIP drive 250.00 14 104 Speaker 550.00 16 105 Monitor 5000.00 11 106 DVD drive 900.00 12 107 CD drive 800.00 12 108 Printer 2600.00 13 109 Refill cartridge 350.00 13 110 Mouse 250.00 12
Sample Solution:
-- This query calculates the average 'pro_price' for each 'pro_com' (Company ID) in the 'item_mast' table.
SELECT AVG(pro_price) AS "Average Price",
pro_com AS "Company ID"
-- Specifies the table from which to retrieve the data (in this case, 'item_mast').
FROM item_mast
-- Groups the result set by the 'pro_com' column.
GROUP BY pro_com;
Output of the Query:
Average Price Company ID 250.0000000000000000 14 650.0000000000000000 12 3200.0000000000000000 15 5000.0000000000000000 11 1475.0000000000000000 13 500.0000000000000000 16
Code Explanation:
The said SQL query that returns the average price of items grouped by company. The query performs the following operations:
Selects the average price of items from the 'item_mast' table using the AVG function and assigns the result to the alias "Average Price".
Selects the company ID of each item from the 'item_mast' table and assigns it to the alias "Company ID".
Groups the results by the "pro_com" column, which represents the company ID of each item.
The final result is a table with two columns, "Average Price" and "Company ID", showing the average price of items for each company.
Practice Online
Query Visualization:
Duration:
Rows:
Cost:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Find the number of products over or equal to Rs 350.
Next SQL Exercise: Calculate the total allotment for all departments.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/sql-exercises/sql-aggregate-function-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics