选择范围内具有最大值的条目数

时间:2015-01-13 14:23:28

标签: sql count range max

我需要得到myIndex的计数,它具有每小时的最大值,例如:

MyIndex f_hour  maxi
8187    10  70**  ++1 for 10h and 8187
8178    10  50
8184    10  46
8190    10  46
8180    10  40
8179    10  33
8185    10  30
8183    10  26
8181    10  23
8182    10  20
8186    10  20
8177    10  13
8189    10  6
8188    10  3
**8188  11  80** ++1 for 11h and index 8188
8187    11  60
8180    11  53
8186    11  50
8179    11  46
8190    11  46
8178    11  43
8181    11  33
8184    11  33
8189    11  33
8183    11  26
8185    11  23
8182    11  16
8177    11  13
**8187  12  73** now 8187 has at 10h the max value and now at 12h too, so 2 !! 
8188    12  66
8179    12  60
8190    12  56

结果将像

MyIndex     Count
8187          2 (times)
8188          1 (time)

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

这是直方图查询的直方图。您似乎想要计算每个值显示为最大值的小时数。这最终成为双group by

select maxvalue, count(*) as numhours
from (select hour, max(value) as maxvalue
      from table t
      group by hour
     ) t
group by maxvalue
order by maxvalue;

编辑:

我知道,你不需要值的直方图,而是索引的直方图。您可以使用窗口函数来执行此操作,这些函数是ANSI标准的,并且在大多数(但不是所有)数据库中都可用:

select myindex, count(*) as numhours
from (select t.*, row_number() over (partition by hour order by value desc) as seqnum
      from table t
      group by hour
     ) t
where seqnum = 1
group by myindex
order by myindex;