Postgresql 问题

问题描述 投票:0回答:3

我有一张这样的桌子:

name   used   time  
asd    10     15:00  
bsf    15     15:00  
asd    20     14:55  
bsf    0      14:55

我需要进行一个返回如下值的查询: 我需要的 grafana 时间序列的结果是:

total   tm
25       15:00
20       14:55 

我尝试过使用:

SELECT
 DISTINCT(time) as tm,
 sum(used) as total
FROM table
GROUP BY tm

但这并不能解决我尝试的所有问题,给我重复的时间值

sql postgresql grafana window-functions gaps-and-islands
3个回答
0
投票

查看 postgres 文档是使用时间戳的一个很好的起点。这是一种按 HH:MI:SS 分组和聚合的方法:


with my_table as (
  select current_timestamp as time_column, 20 as used union all
  select current_timestamp, 5 union all
  select current_timestamp - INTERVAL '10 Seconds', 15
  )
select to_char(time_column,'HH24:MI:SS') as time_col, sum(used) as used
from my_table
group by 1
order by 1;
time_col 二手
19:43:35 15
19:43:45 25

基本上,这种类型的选角是你的朋友:

to_char(time_column,'HH24:MI:SS')

0
投票

我设法通过使用 date_trunc() 函数选择时间值来解决问题,因为该列的类型为 timestamptz,查询最终看起来像这样 选择 date_trunc('分钟', 时间) as tm, 总和(已使用)作为总计 从 桌子 通过...分组 TM


0
投票

您正在寻找一个简单的 GROUP BY

CREATE TABLE Table1
    ("name" varchar(3), "used" int, "time" varchar(5))
;
    
INSERT INTO Table1
    ("name", "used", "time")
VALUES
    ('asd', 10, '15:00'),
    ('bsf', 15, '15:00'),
    ('asd', 20, '14:55'),
    ('bsf', 0, '14:55')
;

SELECT
SUM("used"), "time"
FROM Table1
GROUP BY "time"
总和 时间
25 15:00
20 14:55
SELECT 2

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.