Monday, May 30, 2011

GROUP BY purpose


Group by can't be discussed without appealing to aggregate functions. The main aggregate functions are MIN, MAX, SUM, COUNT, AVG. For visual understanding let's create a test table and fill it in with some test data

CREATE TABLE testgroupby (id INT IDENTITY (1,1) PRIMARY KEY CLUSTERED,city VARCHAR(100) not null,country VARCHAR(100) not null,population INT
 GO
INSERT
INTO testgroupby (city, country, population)SELECT 'kiev', 'ukraine', 5000000UNION ALL SELECT 'odessa', 'ukraine', 1000000UNION ALL SELECT 'moscow', 'russia', 10000000UNION ALL SELECT 'rostov', 'russia', 2000000UNION ALL SELECT 'omsk', 'russia', 2000000UNION ALL SELECT 'los-angeles', 'USA', 15000000UNION ALL SELECT 'New York', 'USA', 20000000UNION ALL SELECT 'Miami', 'USA', 7000000GO


So let's use aggregation functions against the testgroupby table.

SELECT COUNT (*), MIN(population), MAX( population), SUM(population)FROM testgroupby
 
And you will see the next results
)

No comments:

Post a Comment