0

I have a user table that has age column. I need to be able to dynamically create set of ranges and pass it to the procedure, for example:

[
  [0, 10],
  [10, 18],
  [18, 35],
]

As a result, it needs to return values count that belong to each range. Example:

|min|max|count|
---------------
|  0| 10|   24|
| 10| 18|  111|
| 18| 35|    0|

How can I implement such procedure?

1
  • and check if the value within this range - which "value" should be checked? Please edit your question (by clicking on the edit link below it) and add some sample data and the expected output based on that data as formatted text. See here for some tips on how to create nice looking text tables. (edit your question - do not post code or additional information in comments) Commented Aug 4, 2020 at 11:01

1 Answer 1

3

You can create a list of ranges and use that to join to the table then group by the matched range:

with ranges (range) as (
  values 
    ( int4range(10,30) ), 
    ( int4range(10,18) ), 
    ( int4range(18,35) )
)
select r.range, count(t.age)
from ranges r
  left join the_table t on t.age <@ r.range
group by r.range;  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.