Created
August 16, 2021 21:21
-
-
Save DominikStyp/5110c468043a7bbe7b880f2a2c83effb to your computer and use it in GitHub Desktop.
SQL GROUP BY WITH CONDITIONAL SUM (CASE WHEN)
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, | |
day TINYINT, | |
revenue INT | |
); | |
INSERT INTO test (year, month, day, revenue) VALUES | |
(2020, 01, 31, 9000), | |
(2020, 02, 29, 1500), | |
(2020, 02, 30, 2000), | |
(2020, 02, 31, -7500), | |
(2020, 03, 30, 2000), | |
(2020, 03, 31, 1700), | |
(2021, 01, 31, 1000), | |
(2021, 02, 31, 1200), | |
(2021, 03, 31, 1900), | |
(2022, 01, 31, 1000), | |
(2022, 02, 31, 1540), | |
(2021, 03, 31, 1980); |
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 | feb | |
---|---|---|
2020 | -4000 | |
2021 | 1200 | |
2022 | 1540 |
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, SUM(CASE WHEN month = 02 THEN revenue ELSE 0 END) as feb | |
FROM test | |
GROUP BY year; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment