-
Notifications
You must be signed in to change notification settings - Fork 0
/
GROUP_ BY 1 function
43 lines (32 loc) · 1.14 KB
/
GROUP_ BY 1 function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Calculate Aggregate for Data with Certain Characteristics
Example:
We might want to know the mean IMDb ratings for all movies each year. We could calculate each number by a series of queries with different WHERE statements, like so:
SELECT AVG(imdb_rating)
FROM movies
WHERE year = 1999;
SELECT AVG(imdb_rating)
FROM movies
WHERE year = 2000;
SELECT AVG(imdb_rating)
FROM movies
WHERE year = 2001;
OR Reduce the steps BY:
SELECT year,
AVG(imdb_rating)
FROM movies
GROUP BY year
ORDER BY year;
GROUP BY is a clause in SQL that is used with aggregate functions. It is used in collaboration with the SELECT statement to arrange identical data into groups.
The GROUP BY statement comes after any WHERE statements, but before ORDER BY or LIMIT.
Example:
SELECT price, COUNT(*)
FROM fake_apps
GROUP BY price;
The result contains the total number of apps for each price.
It is organized into two columns, making it very easy to see the number of apps at each price.
Example:
Write a new query that calculates the total number of downloads for each category.
Select category and SUM(downloads).
SELECT category, SUM(downloads)
FROM fake_apps
GROUP BY category;