mardi 24 février 2015

Return counts for multiple ranges in a single SELECT statement


I have a Postgres database table foo that, among other things, has a column for score that ranges from 0 - 10. I want a query to return the total number of scores, the number of scores between 0 and 3, the number of scores between 4 and 6, and the number of scores between 7 and 10. Something like the following:



SELECT
COUNT(*) as total,
COUNT(
SELECT * from foo where score between 0 and 3;
) as low,
COUNT(
SELECT * from foo where score between 4 and 6;
) as mid,
COUNT(
SELECT * from foo where score between 7 and 10;
) as high
FROM foo;


I tried this, but got an error with the SELECT in the COUNT statements. Any ideas how I can do this? I'm sure there's a super simple way in Postgres. I just can't figure out the correct terms to Google for.





Aucun commentaire:

Enregistrer un commentaire