简体   繁体   中英

Usage of aggregate function Group by

I have observed that Count function can be used without the usage of aggregate function Group by. Like for example:

Select Count(*) from  Employee 

It would surely return the count of all the rows without the usage of aggregate function. Then where do we really need the usage of group by?

Omitting the GROUP BY implies that the entire table is one group. Sometimes you want there to be multiple groups. Consider the following example:

SELECT month, SUM(sales) AS total_sales
FROM all_sales
GROUP BY month;

This query gives you a month-by-month breakdown of sales. If you omitted month and the GROUP BY clause, you would only receive the total sales of all time which may not have the granularity you require.

You can also group by multiple columns, giving finer detail still:

SELECT state, city, COUNT(*) AS population
FROM all_people
GROUP BY state, city;

Additionally, using a GROUP BY allows us to use HAVING clauses. Which lets us filter groups. Using the above example, we can filter the result to cities with over 1,000,000 people:

SELECT state, city, COUNT(*) AS population
FROM all_people
GROUP BY state, city
HAVING COUNT(*) > 1000000;

The group by clause is used to break up aggregate results to groups of unique values. Eg, let's say you don't want to know how many employees you have, but how many by each first name (eg, two Gregs, one Adam and three Scotts):

SELECT   first_name, COUNT(*)
FROM     employee
GROUP BY first_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM