SQL Data Range Min Max category

旧城冷巷雨未停 提交于 2019-12-06 10:11:10
Gordon Linoff

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!