0

我想得到正确的周数。

使用该to_char函数,该函数枚举从星期一开始的一周,但考虑到一周从星期六开始,我想获得周数。

这是一个例子:

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

4

3 回答 3

3

SELECT EXTRACT(WEEK FROM now());将给出数字 7,表示(目前)我们处于一年中的第 7 周。默认情况下,Postgres 周从星期一开始。

SELECT EXTRACT(WEEK FROM timestamp '2013-01-05');将给出 1,因为自年初以来仅过去了 5 天。

编辑它似乎只从第一个整周过去的时间开始计算周数。在不编写自己的函数的情况下,我建议您使用此函数或使用其他方法来查找它。

于 2013-02-11T18:42:49.917 回答
2

你必须使用extract(doy from ...)extract(dow from ...)加上一些数学。文档中的详细信息。

于 2013-02-11T16:11:48.607 回答
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
于 2013-02-13T15:06:52.790 回答