8

我使用以下查询来获取当前周

select extract(week from current_timestamp)它显示那34很好。

但是我如何获得当前月份的当前周数。

4

6 回答 6

22

您可以通过以下方式找到本周的第一天:

trunc('week', current_date)

本月第一周的第一天:

trunc('week', date_trunc('month', current_date))

将两者相减以找到当月的周数:

extract('day' from date_trunc('week', current_date) -
                   date_trunc('week', date_trunc('month', current_date))) / 7 + 1
于 2013-08-23T10:10:11.427 回答
8

尝试以下

SELECT to_char('2016-05-01'::timestamp, 'W');
于 2016-05-06T16:00:43.847 回答
2

您可以使用 day 来查找周数,例如:

select ((date_part('day', current_date)::integer - 1) / 7) +1;
于 2015-06-24T06:13:39.443 回答
0

我不确定这在 postgreSql (http://www.w3cyberlearnings.com/PostgreSQL_DATE_PART)上如何工作,
但在 sql server 中,示例是这样的......

>SELECT date_part('week', date)
于 2013-08-23T09:48:33.030 回答
0

这将给出准确的结果

CREATE OR REPLACE FUNCTION week_no(date) RETURNS integer AS $BODY$ SELECT CASE WHEN EXTRACT(DAY FROM $1::TIMESTAMP)::INTEGER = 1 THEN 1 ELSE extract(week from $1:: TIMESTAMP)::integer
- extract(week from ( date_trunc('month', $1::TIMESTAMP) + interval '1 day' ) )::integer + 1 END
$BODY$ LANGUAGE sql IMMUTABLE STRICT COST 100;

示例: week_no('2017-01-01') = 1

于 2017-03-27T17:16:26.370 回答
0

也许晚了..但这也有效

其中 cast(call_start as Date) = Date 'today'

或 cast(call_start as Date)= Date 'today' -1

或 cast(call_start as Date)= Date 'today' -2

或 cast(call_start as Date)= Date 'today' -3

或 cast(call_start as Date)= Date 'today' -4

或 cast(call_start as Date)= Date 'today' -5

或 cast(call_start as Date)= Date 'today' -6

或 cast(call_start as Date)= Date 'today' -7

;

这给了我

于 2017-07-18T09:30:13.980 回答