Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Created August 16, 2021 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominikStyp/5110c468043a7bbe7b880f2a2c83effb to your computer and use it in GitHub Desktop.
Save DominikStyp/5110c468043a7bbe7b880f2a2c83effb to your computer and use it in GitHub Desktop.
SQL GROUP BY WITH CONDITIONAL SUM (CASE WHEN)
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);
year feb
2020 -4000
2021 1200
2022 1540
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