1

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

public.schedule_20121018

有没有办法以上述20121018模式生成日期序列,以便我可以进行 forSELECT循环information_schema.tables

现在我有

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

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

4

2 回答 2

3
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;
于 2012-10-19T15:23:58.667 回答
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)
于 2012-10-19T15:23:59.603 回答