问题
I want to determine the range of 2 categories. Category A and Category B. A starts from 1 to 15, B starts from 16 to 31 then A Again starts from 32 to 40. Now If run this query
select min(range), max(range)
from table
group by category
order by category
it gives me Range of category A from 1 to 40 and Category B from 16 to 31. I want to break the Range and want to see the results
Category A 1 to 15
Category B 16 to 31
Category A 32 to 40
How do I do that? Do I need a 3rd column? I know if i have 3rd column with new categories lets say C D E respectively, I can group by those and get the results. but I dont know how to do that.
Please help me out.
Thanks -Adeel
回答1:
Assuming that you are trying to break the categories into groups consisting of consecutive integers, then the following will work:
select category, diff, min(range), max(range)
from
(
select category, range,
(range - row_number() over (partition by category order by range)) as diff
from table
) t
group by category
order by 1, 3
This query is based on the observation that within a given grouping for a category, the numbers increase sequentially. Hence, subtracting a sequence of integer will result in a constant, which can then be used for identifying that particular range.
Row_Number()
is a standard SQL function, so it is available in most databases.
回答2:
It sounds like a recursive CTE should work for you, but it depends on your RDBMS on how this could work (and if it is even supported) But, you could probably do some sort of incremental count that can be used as a multiplier for each piece up until a max limit. If you let us know the RDBMS I can provide an example.
来源:https://stackoverflow.com/questions/10423781/sql-data-range-min-max-category