项目中交易记录进行统计查询时,须要对一段时间连续日期内交易数据进行统计,
由于指定时间段内某些日期可能没有交易数据,因此须要补齐。
使用 postgresql序列生成函数,生成连续日期,再进行查询。 sql
以下: 函数
序列号生成函数 post
函数 |
参数类型 |
返回类型 |
描述 |
generate_series(start,stop) |
int或bigint |
setof int或setof bigint(与参数类型相同)) |
生成一个数值序列,从start到stop,步长为1 。 |
generate_series(start,stop,step) |
int或bigint |
setof int或setof bigint(与参数类型相同)) |
生成一个数值序列,从start到stop,步长为step。 |
generate_series(start,stop,step) |
timestamp或timestamp with time zone |
setof timestamp或setof timestamp with time zone(与参数类型相同) |
生成一个数值序列,从start到stop,步长为step。 |
网上有人的用法(以下),先计算日期相差天数,查询中进行日期累加,我以为反而变复杂了
select to_char(cast('20081001' as date) + s.a,'yyyyMMdd') as 统计日期 from generate_series(0, cast('20081031' as date)-cast('20081001' as date),1) as s(a)
postgresql中给的例子是:
SELECT * FROM generate_series('2008-03-01 00:00'::timestamp, '2008-03-04 12:00', '10 hours');
generate_series ---------------------
2008-03-01 00:00:00
2008-03-01 10:00:00
2008-03-01 20:00:00
2008-03-02 06:00:00
2008-03-02 16:00:00
2008-03-03 02:00:00
2008-03-03 12:00:00
2008-03-03 22:00:00
2008-03-04 08:00:00
(9 rows)
稍做修改以下:
SELECT to_char(a,'yyyyMMdd') FROM generate_series('2008-03-01'::date,'2008-03-04', '1 days') as a;
"20080301"
"20080302"
"20080303"
"20080304"
知足如今使用场景。