prisskreative
1/20/2016 - 6:04 AM

SQL AGGREGATE FUNCTIONS

SQL AGGREGATE FUNCTIONS

// =============================================== //

   AGGREGATE FUNCTIONS
   how to perform calculations using SQL.

// =============================================== //


Aggregate functions combine multiple rows together to form a single value of more meaningful information.

COUNT takes the name of a column(s) as an argument and counts the number of rows where the value(s) is not NULL.

GROUP BY is a clause used with aggregate functions to combine data from one or more columns.

SUM() takes the column name as an argument and returns the sum of all the values in that column.

MAX() takes the column name as an argument and returns the largest value in that column.

MIN() takes the column name as an argument and returns the smallest value in that column.

AVG() takes a column name as an argument and returns the average value for that column.

ROUND() takes two arguments, a column name and the number of decimal places to round the values in that column.



## how many apps are in the database ##

SELECT COUNT(*) FROM fake_apps;


---


## where price is 0 ##

SELECT COUNT(*) FROM fake_apps
WHERE price = 0;


---


## Count the number of apps at each price. ##

SELECT price, COUNT(*) FROM fake_apps
GROUP BY price;


---


## Count the total number of apps at each price that have
   been downloaded more than 20,000 times. ##

SELECT price, COUNT(*) FROM fake_apps
WHERE downloads > 20000
GROUP BY price;


---


## What is the total number of downloads for all of the apps combined? ##

SELECT SUM(downloads) FROM fake_apps;


---


## Calculate the total number of downloads for each category. ##

SELECT category, SUM(downloads) FROM fake_apps
GROUP BY category;


---


## How many downloads does the most popular app have? ##


SELECT MAX(downloads) FROM fake_apps;


---


## What is the least number of times an app has been 
   downloaded?  ##

SELECT name, category, MAX(downloads) FROM fake_apps
GROUP BY category;


---


## Return the names of the apps that have been downloaded 
   the least number of times in each category. ##


SELECT name, category, MIN(downloads) FROM fake_apps
GROUP BY category;


---


## Calculate the average number of downloads for an app in 
   the database.  ##


SELECT AVG(downloads) FROM fake_apps;


---


## Calculate the average number of downloads at each price ##


SELECT price, AVG(downloads) FROM fake_apps
GROUP BY price;

--

## Make the result set more readable by rounding the average 
   number of downloads to two decimal places ##


SELECT price, ROUND(AVG(downloads), 2) FROM fake_apps
GROUP BY price;


--


## Round the average number of downloads to the nearest 
   integer for each price. ##

SELECT price, ROUND(AVG(downloads)) FROM fake_apps
GROUP BY price;