Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count how many rows with one column value have another column value greater than 0 postgresql

Let’s say I have a table like so

Name Value Time
John 7 8am
Mike 2 7am
John 1 4am
Ryan 0 2am

And I would like to query the table to output all the unique names (John, Mike, and Ryan) as well as the number of Value columns each one has that is greater than 0. (NOT the sum of their value columns).

The output should be like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

John 2
Mike 1
Ryan 0

So far I have been able to output the unique names with

SELECT "Name" FROM table GROUP BY "Name"

However the rest escapes me.

Thank you!

>Solution :

You can use FILTER():

SELECT "Name" 
    , COUNT(*) FILTER(WHERE "Value" > 0)
FROM table 
GROUP BY "Name"
ORDER BY 2 DESC; -- 2nd column

Advice: Don’t use UPPER case in your table or column definitions. Such a pain in the *** to keep on using " and " forever…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading