[英]Postgres generate_series() of given length
We can generate a datetime array with specified bin-width using:我们可以使用以下命令生成具有指定 bin 宽度的日期时间数组:
select generate_series(
timestamp without time zone '2020-10-01 00:00:00', '2020-10-04 00:00:00',
'24 hours') as ts
ts
1 2020-10-01
2 2020-10-02
3 2020-10-03
4 2020-10-04
Is it possible to generate an array of set length ie a given number of bins/breaks?是否可以生成设置长度的数组,即给定数量的 bin/breaks?
I want to provide a date range and number of equal intervals to divide it into.我想提供一个日期范围和相等间隔的数量来划分它。
From the comments:来自评论:
I want to provide a date range and number of equal intervals to divide it into我想提供一个日期范围和相等间隔的数量来将它分成
You can use generate_series()
with integers, and date arithmetics:您可以将generate_series()
与整数和日期算术一起使用:
with params as (
select
timestamp '2020-10-01' ts_start,
timestamp '2020-10-04' ts_end,
3 num
)
select ts_start + (ts_end - ts_start) * i / num as ts
from params
cross join lateral generate_series(0, num) s(i)
This splits the given time range into 3 intervals (resulting in a total of 4 timestamps).这将给定的时间范围分成 3 个间隔(总共有 4 个时间戳)。
Demo on DB Fiddle : DB Fiddle 上的演示:
| ts | | :------------------ | | 2020-10-01 00:00:00 | | 2020-10-02 00:00:00 | | 2020-10-03 00:00:00 | | 2020-10-04 00:00:00 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.