Skip to content

Instantly share code, notes, and snippets.

@drorata
Created July 6, 2017 08:07
Show Gist options
  • Select an option

  • Save drorata/bdfa45d1b8076daf493063838939decf to your computer and use it in GitHub Desktop.

Select an option

Save drorata/bdfa45d1b8076daf493063838939decf to your computer and use it in GitHub Desktop.
Count positives and negatives of a value
--- A query that count the number of positive/zero/negatives of the column 'value'
--- and group it by the year-month
WITH t AS
( SELECT value,
YEAR,
MONTH
FROM my_table AS l
)
SELECT YEAR,
MONTH,
sum(CASE
WHEN value > 0 THEN 1
ELSE 0
END) AS positive,
sum(CASE
WHEN value = 0 THEN 1
ELSE 0
END) AS zero,
sum(CASE
WHEN value < 0 THEN 1
ELSE 0
END) AS negative
FROM t
GROUP BY t.YEAR,
t.MONTH
ORDER BY YEAR,
MONTH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment