Cursussen/Courses Codesnippets     Top 
SQL select - Group


Group
To count the number of records you can use the function "count()". All records are counted, even those with the same content (e.g. all cities).
select count(city)
from customer
If you want to know how many DIFFERENT cities there are in the customer table, use the word "DISTINCT". Doubly occurring city names are then not taken into account when running the query.
select count(distinct city)
from customer
If you want to know which cities are correct, you can run the query below.
select distinct city
from customer
You do not yet know how many times a certain name of a city occurs.
To be able to make a combination of these two queries, you must first group the data.
select city, count(city)
from customer
group by city
The query statement must then be extended with "group by". Whenever you use an aggregate function (COUNT, SUM, AVG) you must first group the data by all other fields specified after the word "select".
select wine_name, year, count(year)
from wine
where upper(wine_name) = 'WOODESTOCK'
group by wine_name, year
You cannot use a statistical function in the "where" clause. If you still want to specify a condition, you must enter the word "having" after the "group by" line.
select wine_name
from wine
group by wine_name
having avg(year) > 1988
In this example, the wines are selected with an average age greater than 1988.


X

Paragraphs

Group