Last active
March 25, 2018 15:18
-
-
Save jdw1996/036d10e4a5a32fac218fda6a4a864b29 to your computer and use it in GitHub Desktop.
Code snippets used in my blog post on nesting aggregate functions in SQL: https://jdw1996.github.io/2017-03-26-nesting-sql-aggregate-functions.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create the table to hold our data. | |
CREATE TABLE purchases ( | |
name VARCHAR(5), | |
amount DECIMAL(5,2), | |
year CHAR(4) | |
); | |
-- Insert the example data. | |
INSERT INTO purchases VALUES ( 'Gene', 234.04, '2015'); | |
INSERT INTO purchases VALUES ( 'Paul', 56.99, '2015'); | |
INSERT INTO purchases VALUES ('Peter', 23.95, '2015'); | |
INSERT INTO purchases VALUES ('Peter', 102.76, '2015'); | |
INSERT INTO purchases VALUES ( 'Ace', 5.49, '2016'); | |
INSERT INTO purchases VALUES ( 'Ace', 19.41, '2016'); | |
INSERT INTO purchases VALUES ( 'Ace', 22.77, '2016'); | |
INSERT INTO purchases VALUES ( 'Gene', 166.30, '2016'); | |
INSERT INTO purchases VALUES ( 'Paul', 65.99, '2016'); | |
INSERT INTO purchases VALUES ('Peter', 89.90, '2016'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT year, | |
COUNT(*) AS the_count, | |
SUM(amount) AS the_sum | |
FROM purchases | |
GROUP BY year; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT year, | |
name, | |
COUNT(*) AS the_count, | |
SUM(amount) AS the_sum | |
FROM purchases | |
GROUP BY year, name; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT year, | |
name, | |
SUM(amount) AS numerator, | |
SUM(SUM(amount)) | |
OVER (PARTITION BY year) AS denominator | |
FROM purchases | |
GROUP BY year, name; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT year, | |
name, | |
SUM(amount) | |
* 100.0 | |
/ SUM(SUM(amount)) OVER (PARTITION BY year) | |
AS pct_of_spending | |
FROM purchases | |
GROUP BY year, name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment