DavidSzczesniak
1/23/2018 - 2:42 PM

GROUP BY

Used along with SELECT to arrange identical data into groups. Allows us to edit/manipulate certain groups of data easily.

\!h Example - count the total number of apps for each price in the table
SELECT price, COUNT(*)
FROM fake_apps
GROUP BY price; -- shows the result for every price

-- Output:

price | COUNT(*)
------+------------
1.99  | total number of apps that cost £1.99
2.99  | ...
5.99  | ...
...   | ...

\!h Column references:
 -- How many movies have IMDb ratings that round to 1, 2, 3, 4, 5, the long way:
 SELECT ROUND(imdb_rating),
    COUNT(name)
 FROM movies
 GROUP BY ROUND(imdb_rating)
 ORDER BY ROUND(imdb_rating);

-- Using column references:
 SELECT ROUND(imdb_rating),
    COUNT(name)
 FROM movies
 GROUP BY 1
 ORDER BY 1; -- 1 = first column selected, 2 would = second column selected and so on...