-
Notifications
You must be signed in to change notification settings - Fork 0
/
Group By 2 Function
43 lines (32 loc) · 1 KB
/
Group By 2 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
Sometimes, we want to GROUP BY a calculation done on a column.
For instance, we might want to know how many movies have IMDb ratings that round to 1, 2, 3, 4, 5. We could do this using the following syntax:
SELECT ROUND(imdb_rating),
COUNT(name)
FROM movies
GROUP BY ROUND(imdb_rating)
ORDER BY ROUND(imdb_rating);
However, this query may be time-consuming to write and more prone to error.
SQL lets us use column reference(s) in our GROUP BY that will make our lives easier.
1 is the first column selected
2 is the second column selected
3 is the third column selected
Example:
SELECT ROUND(imdb_rating),
COUNT(name)
FROM movies
GROUP BY 1
ORDER BY 1;
Here, the 1 refers to the first column in our SELECT statement, ROUND(imdb_rating).
Example:
SELECT category,
price,
AVG(downloads)
FROM fake_apps
GROUP BY category, price;
Write the exact query, but use column reference numbers instead of column names after GROUP BY.
Query:
SELECT category,
price,
AVG(downloads)
FROM fake_apps
GROUP BY 1, 2;