fullstack_webdev

Code and notes from Full stack web developer path, LinkedIn Learning.

View on GitHub

08. Aggregates

08_01 What are aggregates ?

-- Groups the count of countries in a region in desc order
SELECT Region, COUNT(*) AS Count
    FROM Country
    GROUP BY Region
    ORDER BY Count DESC, Region
;

-- Album DB - Find how many tracks each album has, we group by album id and order by number of tracks
SELECT a.title AS Album, COUNT(t.track_number) as Tracks
  FROM track AS t
  JOIN album AS a
    ON a.id = t.album_id
  GROUP BY a.id
  ORDER BY Tracks DESC, Album
;
SELECT a.title AS Album, COUNT(t.track_number) AS Tracks
  FROM track AS t
  JOIN album AS a
    ON a.id = t.album_id
  GROUP BY a.id
  HAVING Tracks >= 10
  ORDER BY Tracks DESC, Album
;
SELECT a.title AS Album, COUNT(t.track_number) as Tracks
  FROM track AS t
  JOIN album AS a
    ON a.id = t.album_id
  WHERE a.artist = 'The Beatles'
  GROUP BY a.id
  HAVING Tracks >= 10
  ORDER BY Tracks DESC, Album
;

08_02 Using aggregate functions

SELECT COUNT(Population) FROM Country;
SELECT AVG(Population) FROM Country;
SELECT Region, ROUND(AVG(Population),2) AS 'Avg. Population' FROM Country GROUP BY Region;
SELECT Region, MIN(Population), MAX(Population) FROM Country GROUP BY Region;
SELECT Region, SUM(Population) FROM Country GROUP BY Region;

08_03 Aggregating on Distinct Values

--Count columns that have a value for HeadOfState
SELECT COUNT(HeadOfState) FROM Country;
-- Shows us that there are lots of duplicate values as individuals like Elisabeth II are head of multiple states
SELECT Name,HeadOfState FROM Country ORDER BY HeadOfState;
--To Count Distinct values only we do following:
SELECT COUNT(DISTINCT(HeadOfState)) FROM Country;