Instruction
Welcome to the second part of the SQL Practice Set in MS SQL Server. Now we will focus on aggregation and grouping. However, we'll start with a quick recap.
- SQL offers aggregate functions that can help with computing statistics:
COUNT(),SUM(),MIN(),MAX(),AVG(), etc. - In order to create more sophisticated statistics with aggregate functions, you have to use the
GROUP BYclause. This groups together all rows that have the same values. - You can use the
HAVINGclause, if you need to filter the result of an aggregate function.
Take a look at the example below. This query selects every ClientId and the average value of all items a given client ordered. It takes into consideration only those clients who ordered at least twice.
SELECT ClientId, avg(OrderPrice) FROM ClientOrders GROUP BY ClientId HAVING count(ClientId) >= 2
- The
DISTINCTkeyword eliminates duplicate results. - In order to sort table rows, you need to use the
ORDER BYclause. For example:SELECT ClientId, Name FROM ClientOrders ORDER BY Name DESC
Exercise
Click the button to continue.



