I used following query to get current week
select extract(week from current_timestamp)
and it is showing 34
thats fine.
But how do i get the current week number of the current month.
I used following query to get current week
select extract(week from current_timestamp)
and it is showing 34
thats fine.
But how do i get the current week number of the current month.
You can find the first day of this week with:
trunc('week', current_date)
And the first day of the first week of this month with:
trunc('week', date_trunc('month', current_date))
Subtract the two to find the in-month weeknumber:
extract('day' from date_trunc('week', current_date) -
date_trunc('week', date_trunc('month', current_date))) / 7 + 1
Try the following
SELECT to_char('2016-05-01'::timestamp, 'W');
You can find week number by using day as well like:
select ((date_part('day', current_date)::integer - 1) / 7) +1;
Im not sure on how does this work on postgreSql (http://www.w3cyberlearnings.com/PostgreSQL_DATE_PART)
but in sql server the example is something like this...
>SELECT date_part('week', date)
This will give accurate results
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;
Example: week_no('2017-01-01') = 1
where cast(call_start as Date) = Date 'today'
or cast(call_start as Date)= Date 'today' -1
or cast(call_start as Date)= Date 'today' -2
or cast(call_start as Date)= Date 'today' -3
or cast(call_start as Date)= Date 'today' -4
or cast(call_start as Date)= Date 'today' -5
or cast(call_start as Date)= Date 'today' -6
or cast(call_start as Date)= Date 'today' -7
;
this gives me it