我想得到正确的一周数字。
使用to_char
函数,该函数枚举以mondey开头的一周,但我想得到周数,考虑周六开始一周。
以下是一个例子:
SELECT to_char('05-01-2013'::date,'daydd-mm-yyyy') as date_char, to_char('05-01-2013'::date,'IW') as week_number
结果:
"saturday 05-01-2013";"01"
应该是:
"saturday 05-01-2013";"02"
有没有办法得到它?
配置信息:Windows 7下的Postgresql 9.2
答案 0 :(得分:3)
SELECT EXTRACT(WEEK FROM now());
将给出数字7,表示(目前)我们处于一年的第7周。
Postgres周默认星期一开始。
SELECT EXTRACT(WEEK FROM timestamp '2013-01-05');
将在今年年初仅过去5天后给出1。
编辑它似乎只开始计算从第一个完整周过去的几周。如果不编写自己的函数,我建议使用它或使用不同的方法来查找它。
答案 1 :(得分:2)
您必须使用extract(doy from ...)
和extract(dow from ...)
以及一些数学运算。详情请见documentation。
答案 2 :(得分:0)
这将给出正确的结果:
with first_friday as (
select extract(doy from min(a)::date) ff
from generate_series('2013-01-01'::date, '2013-01-07', '1 day') s(a)
where extract(dow from a) = 5
)
select
to_char(a, 'day'),
a::date "day",
floor((extract(doy from a) - (select ff from first_friday) - 1) / 7) + 2 week_number
from generate_series('2013-01-01'::date, '2013-01-31', '1 day') s(a)
;
to_char | day | week_number
-----------+------------+-------------
tuesday | 2013-01-01 | 1
wednesday | 2013-01-02 | 1
thursday | 2013-01-03 | 1
friday | 2013-01-04 | 1
saturday | 2013-01-05 | 2
sunday | 2013-01-06 | 2
monday | 2013-01-07 | 2
tuesday | 2013-01-08 | 2
wednesday | 2013-01-09 | 2
thursday | 2013-01-10 | 2
friday | 2013-01-11 | 2
saturday | 2013-01-12 | 3
sunday | 2013-01-13 | 3
monday | 2013-01-14 | 3
tuesday | 2013-01-15 | 3
wednesday | 2013-01-16 | 3
thursday | 2013-01-17 | 3
friday | 2013-01-18 | 3
saturday | 2013-01-19 | 4
sunday | 2013-01-20 | 4
monday | 2013-01-21 | 4
tuesday | 2013-01-22 | 4
wednesday | 2013-01-23 | 4
thursday | 2013-01-24 | 4
friday | 2013-01-25 | 4
saturday | 2013-01-26 | 5
sunday | 2013-01-27 | 5
monday | 2013-01-28 | 5
tuesday | 2013-01-29 | 5
wednesday | 2013-01-30 | 5
thursday | 2013-01-31 | 5