Created
August 16, 2021 20:50
-
-
Save DominikStyp/29ad6060c2996f6223a2b29a72676367 to your computer and use it in GitHub Desktop.
SQL GROUP BY WITH ROLLUP: Grouping by multiple columns and rolling up to one
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 TABLE test ( | |
id INT PRIMARY KEY AUTO_INCREMENT, | |
year SMALLINT, | |
month TINYINT, | |
revenue INT | |
); | |
INSERT INTO test (year, month, revenue) VALUES | |
(2020, 01, 900), | |
(2020, 02, 1500), | |
(2021, 01, 1000), | |
(2021, 02, 1200), | |
(2022, 01, 1000), | |
(2022, 02, 1300); |
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
year | month | sum(revenue) | |
---|---|---|---|
2020 | 1 | 900 | |
2020 | 2 | 1500 | |
2020 | null | 2400 | |
2021 | 1 | 1000 | |
2021 | 2 | 1200 | |
2021 | null | 2200 | |
2022 | 1 | 1000 | |
2022 | 2 | 1300 | |
2022 | null | 2300 | |
null | null | 6900 |
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, month, sum(revenue) | |
FROM test | |
GROUP BY year, month WITH ROLLUP; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment