我有例如停电开始日期时间:' 2017-09-09 06:56:22'和结束日期时间:' 2017-09-13 14:22:45'。 现在我想得到停电时间每日,如果整个停电然后给我' 00:00:00'但是如果只有一天的部分时间中断,那么我们做减法ex:startTime - DayEndTime(StartTime),即该开始日结束时的00:00:00。 因此,如果全天中断,那么每天都将计算24:00:00。
我如何在postgresql中解决这个问题?请帮忙
见下表
StartTime EndTime OutageTime
2017-09-09 6:56:32 2017-09-10 0:00:00 17:03:28
2017-09-10 0:00:00 2017-09-11 0:00:00 24:00:00
2017-09-11 0:00:00 2017-09-12 0:00:00 24:00:00
2017-09-12 0:00:00 2017-09-13 0:00:00 24:00:00
2017-09-13 0:00:00 2017-09-13 14:22:45 14:22:45
答案 0 :(得分:1)
您只需计算差异,只需一整天即可将其替换为sample.config
:
24:00:00
答案 1 :(得分:0)
您可以使用generate_series()
执行此操作。以下是每天获得结果的逻辑:
select (case when date_trunc('day', g.dte) = date_trunc('day', o.start_time)
then g.dte
else date_trunc('day', g.dte)
end),
(case when date_trunc('day', g.dte) < date_trunc('day', o.end_time)
then date_trunc('day', g.dte) + interval '1 day'
else o.end_time
end)
from outages o, lateral
generate_series(start_time, end_time, interval '1 day') g(dte)
where g.dte < o.end_time;
您可以使用子查询来获取每天的范围。
答案 2 :(得分:0)
with t (startTime, endTime) as (values
('2017-09-09 6:56:32'::timestamptz,'2017-09-10 0:00:00'::timestamptz),
('2017-09-10 0:00:00','2017-09-11 0:00:00'),
('2017-09-11 0:00:00','2017-09-12 0:00:00'),
('2017-09-12 0:00:00','2017-09-13 0:00:00'),
('2017-09-13 0:00:00','2017-09-13 14:22:45'))
select startTime, endTime, upper(i) - lower(i) as a
from
(
select tstzrange(startTime, endTime) as tstzr, startTime, endTime
from t
) t
inner join (
select tstzrange(d, d + interval '1 day') as d
from
generate_series (
(select min(startTime)::date from t),
(select max(endTime) from t),
'1 day'
) gs (d)
) gs on d && tstzr
cross join lateral (
select tstzr * d as i
) cjl
;
starttime | endtime | a
------------------------+------------------------+----------
2017-09-09 06:56:32-03 | 2017-09-10 00:00:00-03 | 17:03:28
2017-09-10 00:00:00-03 | 2017-09-11 00:00:00-03 | 1 day
2017-09-11 00:00:00-03 | 2017-09-12 00:00:00-03 | 1 day
2017-09-12 00:00:00-03 | 2017-09-13 00:00:00-03 | 1 day
2017-09-13 00:00:00-03 | 2017-09-13 14:22:45-03 | 14:22:45