2012-10-19 163 views
1

我有一系列的按日期劃分和命名的格式如下表日期的順序:生成用於在for循環

public.schedule_20121018 

有沒有一種方法來生成日期在上面20121018模式的順序,從而我可以做一個循環SELECTinformation_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天的記錄,這樣的日期順序應當從開始到2012101220121018。謝謝!

回答

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; 
+0

謝謝Clodoaldo。我嘗試過'to_char',但它給'ERROR:函數的多個小數點「to_char」'。你有沒有在你的機器上試過它,還是應該使用其他一些功能?我懷疑這是我使用較低的Postgresql版本8.2?謝謝! – Rock

+0

@Rock增加了舊版postgresql版本的版本。 –

+0

非常感謝Clodoaldo。我以另一種方式計算出它的結果:'select * fromge(*)'的日期,作爲s(a)選擇regexp_replace((current_date + sa),' - ','','g')''但你的更清潔。謝謝! – Rock

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)