【问题标题】:Generate sequence of dates used in for loop生成用于 for 循环的日期序列
【发布时间】:2012-10-19 23:57:24
【问题描述】:

我有一系列按日期分区并按以下格式命名的表:

public.schedule_20121018

有没有办法在上述20121018 模式中生成日期序列,以便我可以在SELECTinformation_schema.tables 之间进行for 循环?

现在我有

SELECT * FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema = 'public'
AND table_name like 'schedule_%'
ORDER BY table_name;

但例如我需要最近 7 天的记录,以便日期序列应从 20121012 开始到 20121018。谢谢!

【问题讨论】:

    标签: postgresql time-series


    【解决方案1】:
    SELECT *
    FROM information_schema.tables
    WHERE table_type = 'BASE TABLE'
        AND table_schema = 'public'
        AND table_name in (
            select 'schedule_' || to_char(d, 'YYYYMMDD')
            from 
            generate_series(current_date - 7, current_date - 1, '1 day') s(d)
            )
    ORDER BY table_name;
    

    旧的 Postgresql 版本:

    SELECT *
    FROM information_schema.tables
    WHERE table_type = 'BASE TABLE'
        AND table_schema = 'public'
        AND table_name in (
            select 'schedule_' || to_char(current_date - d, 'YYYYMMDD')
            from 
            generate_series(7, 1, -1) s(d)
            )
    ORDER BY table_name;
    

    【讨论】:

    • 谢谢 Clodoaldo。我试过to_char,但它给出了ERROR: multiple decimal points for function "to_char"。您是否在您的机器上尝试过或者我应该使用其他一些功能?我怀疑我使用的是较低的 Postgresql 版本 8.2?谢谢!
    • @Rock 为旧的 postgresql 版本添加了一个版本。
    • 非常感谢 Clodoaldo。我以另一种方式解决了select regexp_replace((current_date + s.a), '-', '', 'g') as dates from generate_series(-7,-1,1) as s(a);,但你的更干净。谢谢!
    【解决方案2】:

    使用generate_series,可能与to_char 一起用于格式化。

    regress=# select generate_series(DATE '20121012', DATE '20121018', interval '1' day);
        generate_series     
    ------------------------
     2012-10-12 00:00:00+08
     2012-10-13 00:00:00+08
     2012-10-14 00:00:00+08
     2012-10-15 00:00:00+08
     2012-10-16 00:00:00+08
     2012-10-17 00:00:00+08
     2012-10-18 00:00:00+08
    (7 rows)
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 1970-01-01
      • 2012-07-29
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多