postgresql - 列的总和,以及按日期时间分组

时间:2017-08-02 02:13:46

标签: sql postgresql

我将数据存储在以下格式中:

         readiops   |        timestamp 
          3.21          2017-05-26 04:01:00
          5.00          2017-05-26 04:41:00 
          2.12          2017-05-26 03:41:00
          3.00          2017-05-26 03:10:00
          4.00          2017-05-26 03:22:00
          2.33          2017-05-26 02:22:00
          4.21          2017-05-26 02:27:00 
          4.21          2017-05-26 02:27:00 

我想获得一个隔离数据,即每小时给定日期的readiops总和。

所以从上面的记录中我想得到以下结果:

          hour_of_day             |       sum_readiops 
           4                              8.21 
           3                              9.12
           2                              10.75

以下是我在postgresql中的查询:

select sum(cast (readiops as float )) as sum_readiops, 
       extract(hour from date_time) as hour_of_day
from table
where date(date_time) = '2017-05-26'
group by extract(hour from date_time)

我得到的输出真的很荒谬而且计数不匹配。有人请帮忙,因为我不确定我的查询中出了什么问题。

2 个答案:

答案 0 :(得分:1)

要解决您的麻烦,请转到以下提供的解决方案

select  extract(hour from event_time) as hour_of_day ,
        sum(cast (event_data as numeric))

from temp
    group by extract(hour from event_time) 
    order by hour_of_day desc

答案 1 :(得分:0)

使用以下查询:

   select format(sum(readiops),2) as sum_readiops,
   extract(hour from timestamp) as hour_of_day
   from table
   where date(timestamp) = '2017-05-26'
   group by extract(hour from timestamp);