计算一个变量的出现次数

时间:2019-11-03 19:09:39

标签: sql postgresql

我的postgres数据库中有一个表,我的系统每5秒钟记录一次变量状态。我需要计算一天中几个小时中发生的“值= 1”变量的出现次数。也就是说,在一天的24小时内,我的变量以“ value = 1”停留了几个小时。

根据附图,我的选择应返回“ 2019-10-31 1”和“ 2019-11-02 01”

我不知道我是否足够清楚。希望如此。

enter image description here

3 个答案:

答案 0 :(得分:2)

如果仅将结果过滤到gcc -I ../lib/ -c max_heap_driver_program.c = 1的那些结果,并得到截断到最接近的小时的gcc -o max_heap_driver_program max_heap_driver_program.o max_heap.o -lm s的唯一列表,则它将是所有白天的列表。发生了1次。如果我们然后将其转换为日期,以至于浪费了小时,将其分组并计数,那么您将获得一天中的小时数,其中值为1:

value

如果正如评论者所要求的那样,如果您只寻找值为1的小时数,那么我们可以执行以下操作:

read_date

内部查询仅生成最小和最大SELECT d::date, count(*) FROM ( SELECT DISTINCT date_trunc('hour', read_date) as d FROM table WHERE value = 1 ) x GROUP BY d::date 为1的那些小时的列表。与1的任何偏差都将导致其中之一为假

答案 1 :(得分:1)

  

也就是说,在一天的24小时内,我的变量在“值= 1”的情况下停留了几小时

您可以使用:

select read_date::date,
       count(distinct date_trunc('hour', read_date)) filter (where value = 1) as num_hours
from t
group by read_date::date;

答案 2 :(得分:0)

这就是您要寻找的东西

select date(DATE_TRUNC('day', dat)) as "Date we checking"
      , sum(difference) as "Number of occurrences"
from (
select DATE_TRUNC('hour', read_date) dat
       , DATE_TRUNC('hour', LAG(read_date) OVER (ORDER BY id)) prev_date
       , extract(hour from DATE_TRUNC('hour', read_date) - DATE_TRUNC('hour', LAG(read_date) OVER (
      ORDER BY id))) difference
from system) t
where difference <= 1
and dat between '2019-10-31 09:00:00' and '2019-11-01 09:00:00'
group by DATE_TRUNC('day', dat);

使用此行定义要检查的24小时:

and dat between '2019-10-31 09:00:00' and '2019-11-01 09:00:00'