Perhaps, I’m overthinking this, but I can’t seem to figure out how to take a list of decimals and group it into data ranges and get a count for each range. Ideally, I would want the minimum value to always be zero regardless of the selected data, and the max should be the max value of the data set. Then I should be able to provide a divisor which would define how many groups I want the data to be divided into. I would prefer not to use a temp table is possible
sample set:
150.75
250.01
600.10
900.50
The output with a divisor of 2 would be:
| RangeStart | RangeEnd | Count |
| ---------- | -------- | ----- |
| 0 | 450.25 | 2 |
| 450.26 | 1000 | 2 |
2
Answers
Here is the query:
You need to replace
table_name
andcolumn_name
with proper names.Short explanation:
I use (nested)
WITH
queries. First nameddatas
is used to pass the parameter how many groups you want to divide to (10 in this example), and to count the maximum value from the dataset.The second
WITH
query (ranges
) is used to get minimum and maximum value of each group. I usegroup_no
for easy grouping.And the main query JOINS the data table with groups definitions (notice the join condition), and counts rows in each group.
Have fun 😉
Define value ranges for group as (group_number-1)*step->(group_number)*step.
Group_numbers from 1 to groupCount.
Step is max(value)/groupCount.
Join ranges with source table and group by group_number.
See example
Demo