Creating a PostgreSQL `tsrange` from two timestamps - postgresql

I am trying to create a tsrange (last Thursday to the previous Thursday) in a postgresql query but I get cast errors.
This is what I have got so far (starting off from this SO question).
WITH past_week AS (
SELECT date_trunc('day', NOW() + (s::TEXT || ' day')::INTERVAL)::TIMESTAMP(0) AS day
FROM generate_series(-7, 0, 1) AS s)
SELECT (
date_trunc('day', (SELECT day FROM past_week WHERE EXTRACT(DOW FROM day) = '4') - '7 day'::INTERVAL),
date_trunc('day', (SELECT day FROM past_week WHERE EXTRACT(DOW FROM day) = '4')));
And this is the result (correct value, but not format, since it's not a range):
row
-----------------------------------------------
("2015-10-29 00:00:00","2015-11-05 00:00:00")
(1 row)
Now, there are 2 main things that bug me:
If I try and add a ::tsrange right before the end of the query, the interpreter complains that:
ERROR: cannot cast type record to tsrange
LINE 6: ...ROM past_week WHERE EXTRACT(DOW FROM day) = '4')))::tsrange;
I would love to avoid repetition, but I'm not that proficient in SQL to know how. Any improvement is more than welcome.

Use tsrange() constructor:
WITH past_week AS (
SELECT date_trunc('day', NOW() + (s::TEXT || ' day')::INTERVAL)::TIMESTAMP(0) AS day
FROM generate_series(-7, 0, 1) AS s)
SELECT tsrange(
date_trunc('day',
(SELECT day FROM past_week
WHERE EXTRACT(DOW FROM day) = '4') - '7 day'::INTERVAL),
date_trunc('day',
(SELECT day FROM past_week
WHERE EXTRACT(DOW FROM day) = '4')));
tsrange
-----------------------------------------------
["2015-10-29 00:00:00","2015-11-05 00:00:00")
(1 row)
Using CURRENT_DATE your query may be as simple as:
WITH previous_thursday AS (
SELECT CURRENT_DATE- EXTRACT(DOW FROM CURRENT_DATE)::int+ 4 AS thursday
)
SELECT tsrange(thursday- '7d'::INTERVAL, thursday)
FROM previous_thursday;

Related

Dynamic value passing in Postgres

Here is a complex query where i need to pass some dates as dynamic to this, As of now i have hardcoded this '2021-08-01' AND '2022-07-31' these 2 dates.
But i have to pass this dates dynamically in such a way that next dates ie, 2022-06 month , thew dates passed will be '2021-07-01' and '2022-06-30' , basically 12 months behind data.
if we take 2022-05 then the passed date should be '2021-06-01' and '2022-05-31'.
How can we achieve this ? Any suggestions or help will be much appreciated.
below is the query for reference
WITH base as
(
SELECT created_at as period ,order_number, TRIM(email) as email ,is_first_order
FROM orders
WHERE created_at::DATE BETWEEN '2021-08-01' AND '2022-07-31'
)
,base_agg as
(
select TO_CHAR(period,'YYYY-MM') as period
,COUNT(DISTINCT email)FILTER(WHERE is_first_order IS TRUE) as new_users
,COUNT(DISTINCT order_number)FILTER(WHERE is_first_order IS FALSE) as returning_orders
FROM base
GROUP BY 1
)
,base_cumulative as
(
SELECT ROW_NUMBER() OVER(ORDER BY PERIOD DESC ) as rno
,period
,new_users
,returning_orders
,sum("new_users")over (order by "period" asc rows between unbounded preceding and current row) as "cumulative_total"
from base_agg
)
SELECT
(SELECT period FROM base_cumulative WHERE rno=1) period
,(SELECT cumulative_total FROM base_cumulative WHERE rno=1) as cumulated_customers
,SUM(returning_orders) as returning_orders
,SUM(returning_orders)/NULLIF((SELECT cumulative_total FROM base_cumulative WHERE rno=1),0) as rate
FROM base_cumulative
You can calculate the end of current month based on NOW() and some logic, the same can be applied with the rest of the calculation
select date_trunc('month', now())::date + interval '1 month - 1 day' end_of_this_month,
date_trunc('month', now())::date + interval '1 month - 1 day'::interval - '1 year'::interval + '1 day'::interval first_day_of_prev_year_month
;
Result
end_of_this_month | first_day_of_prev_year_month
---------------------+------------------------------
2022-08-31 00:00:00 | 2021-09-01 00:00:00
(1 row)

How can i get a week range for a given month in Postgress

This is my current implementation
SELECT
date_trunc('month', do_date::date)::date as starting_of_the_month,
(date_trunc('month', do_date::date) + interval '1 month' - interval '1 day')::date as ending_of_the_month,
case when 1 + FLOOR((EXTRACT(DAY FROM do_date) - 1) / 7) = 1
THEN date_trunc('week', do_date)::date || ' - ' ||
(date_trunc('week', do_date) + '6 days') ::date end as week1,
case when 1 + FLOOR((EXTRACT(DAY FROM do_date) - 1) / 7) = 2
THEN date_trunc('week', do_date)::date || ' - ' ||
(date_trunc('week', do_date) + '6 days') ::date end as week2,
case when 1 + FLOOR((EXTRACT(DAY FROM do_date) - 1) / 7) = 3
THEN date_trunc('week', do_date)::date || ' - ' ||
(date_trunc('week', do_date) + '6 days') ::date end as week3,
case when 1 + FLOOR((EXTRACT(DAY FROM do_date) - 1) / 7) = 4
THEN date_trunc('week', do_date)::date || ' - ' ||
(date_trunc('week', do_date) + '6 days') ::date end as week4,
case when 1 + FLOOR((EXTRACT(DAY FROM do_date) - 1) / 7) = 5
THEN date_trunc('week', do_date)::date || ' - ' ||
(date_trunc('week', do_date) + '6 days') ::date end as week5
FROM sales_dos
WHERE date_trunc('month', do_date::date)::date >= '2021-02-01' AND date_trunc('month', do_date::date)::date < '2021-02-28'
This is my output for now :
I want the output to display as below :
Week 1 : 2021-02-01 - 2021-02-07
Week 2 : 2021-02-08 - 2021-02-14
Week 3 : 2021-02-15 - 2021-02-21
Week 4 : 2021-02-22 - 2021-02-28
Week 5 : -
Here is another way to do it (example for January 2021).
with
t as (select date_trunc('month', '2021-03-11'::date) as aday), -- any date in Jan-2021
s as
(
select d::date, d::date + 6 ed, extract('isodow' from d) wd
from t, generate_series (aday, aday + interval '1 month - 1 day', interval '1 day') d
)
select format ('Week %s', extract(day from d)::integer / 7 + 1) as weekname, d, ed
from s
where wd = 1;
So what you are looking for is a hybrid ISO with standard Calendar. You are taking the ISO week starting and ending period, but instead of all weeks being exactly 7 days you potentially truncate the 1st and/or last weeks.
The change to need for this is not actually extensive. For initial query returns the in the ISO week begin date instead of the 1st of the month. Then the main query then checks for week 1 and if so produces the 1st of the month. The only twist is determining the ISO week begin date. For this I've just included a function I have had for some time specifically for that. The change to the week_days function are marked --<<<.
create or replace function iso_first_of_week(date_in date)
returns date
language sql
immutable strict
/*
Given a date return the 1st day of the week according to ISO-8601.
I.e. Return the Date if it is Monday otherwise return the preceding Monday
*/
AS $$
with wk_adj(l_days) as (values (array[0,1,2,3,4,5,6]))
select date_in - l_days[ extract (isodow from date_in)::integer ]
from wk_adj;
$$;
create or replace
function week_dates( do_date_in date)
returns table (week_num integer, first_date date, last_date date)
language sql
immutable strict
as $$
with recursive date_list(week_num,first_date,terminate_date) as
( select 1
, iso_first_of_week(do_date_in)::timestamp --<<<
, (date_trunc('month', do_date_in) + interval '1 month' - interval '1 day')::timestamp
union all
select week_num+1, (first_date+interval '7 day'), terminate_date
from date_list
where first_date+interval '6 day' < terminate_date::timestamp
)
select week_num
, case when week_num = 1 --<<<
then date_trunc('month', do_date_in)::date --<<<
else first_date::date --<<<
end --<<<
, case when (first_date+interval '6 day')::date > terminate_date
then terminate_date::date
else (first_date+interval '6 day')::date
end last_date
from date_list;
$$;
---------- Original Reply
You can use a recursive query CTE to get the week number and first date for each week of the month specified. The main query calculates the ending date, shorting the last if necessary. Then wrap that into a SQL function to return the week number and date range for each week. See example.
create or replace
function week_dates( do_date_in date)
returns table (ween_num integer, first_date date, last_date date)
language sql
immutable strict
as $$
with recursive date_list(week_num,first_date,terminate_date) as
( select 1
, date_trunc('month', do_date_in)::timestamp
, (date_trunc('month', do_date_in) + interval '1 month' - interval '1 day')::timestamp
union all
select week_num+1, (first_date+interval '7 day'), terminate_date
from date_list
where first_date+interval '6 day' < terminate_date::timestamp
)
select week_num
, first_date::date
, case when (first_date+interval '6 day')::date > terminate_date
then terminate_date::date
else (first_date+interval '6 day')::date
end last_date
from date_list;
$$;
Response to: "How can i put the output in a single row with week1, week2, week3, week4 and week5". This is essentially the initial output that did not satisfy what you wanted. The term for this type action is PIVOT and is generally understood. It stems from transforming row orientation to column orientation. It is not overly difficult but it is messy.
IMHO this is something that belongs in the presentation layer and is not suitable for SQL. After all you are rearranging the data structure for presentation purposes. Let the database server use its natural format, use the presentation layer to reformat. This allows reuse of the queries instead of rewriting when the presentation is changed or another view of the same data is required.
If you actually want this then just use your initial query, or see the answer from
#Bohemian. However the below shows how this issue can be handled with just SQL (assuming the function week_dates was created).
select week1s
, case when week5e is null
then week4e
else week5e
end "end of month"
, week1s || ' - ' || week1e
, week2s || ' - ' || week2e
, week3s || ' - ' || week3e
, week4s || ' - ' || week4e
, week5s || ' - ' || week5e
from ( select max(case when (week_num=1) then first_date else NULL end) as week1s
, max(case when (week_num=1) then last_date else NULL end) as week1e
, max(case when (week_num=2) then first_date else NULL end) as week2s
, max(case when (week_num=2) then last_date else NULL end) as week2e
, max(case when (week_num=3) then first_date else NULL end) as week3s
, max(case when (week_num=3) then last_date else NULL end) as week3e
, max(case when (week_num=4) then first_date else NULL end) as week4s
, max(case when (week_num=4) then last_date else NULL end) as week4e
, max(case when (week_num=5) then first_date else NULL end) as week5s
, max(case when (week_num=5) then last_date else NULL end) as week5e
from week_dates(current_date)
) w ;
As before I have wrapped the above in a SQL function and provide an example here.
I would first simplify to:
extract(day from do_date)::int / 7 + 1 as week_in_month
then pivot on that using crosstab().

Generate calendar with postgresql

I'm trying to write query which shows calendar in format:
mon. thues. wen. th. fri. sat. sun.
First value in current week is always monday.
For instance, today is friday - 24-07-2015, so i need first value to be 20-07-2015 and the last one 26-07-2015
Until now, I came up with this:
SELECT
extract(DOW FROM r.e - s.a) w,
r.e - s.a as dates
FROM generate_series(0,7,1) AS s(a),
(SELECT CURRENT_DATE e) r
WHERE extract(DOW FROM CURRENT_DATE - s.a) >=1
GROUP BY 1,2;
and then I could sort it with distinct and then substract sunday in the same way. But maybe you can suggest some more elegant solution?
Basically I would like to find the date of closest monday and closest sunday.
Ok, I've managed it:
WITH monday AS (
SELECT
r.e - s.a as dow
FROM generate_series(0,6,1) AS s(a),
(SELECT CURRENT_DATE e) r
WHERE extract(DOW FROM CURRENT_DATE - s.a) = 1
), sunday as (
SELECT
r.e + s.a as dow
FROM generate_series(0,6,1) AS s(a),
(SELECT CURRENT_DATE e) r
WHERE extract(DOW FROM CURRENT_DATE + s.a) = 0
), columns AS(
SELECT n::date
FROM generate_series((select dow from monday), (select dow from sunday), $$1 day$$) n
) SELECT n FROM columns;

PgSQL turning day-of-year back into date

I am trying to determine how to turn a day-of-year back into a date in PgSQL. When I do this
select date '2013-01-01' + interval '53 days'
I get a timestamp:
"2013-02-23 00:00:00"
So how come when I do any of the following
select extract(date from (date '2013-01-01' + interval '53 days'))
select extract(date from (select date '2013-01-01' + interval '53 days'))
I get "ERROR: timestamp units "date" not recognized"? Besides the why, how can I do what I want, which is to only get the date portion of the result of the original operation?
Use
select (date '2013-01-01' + interval '53 days')::date
or
select cast(date '2013-01-01' + interval '53 days' as date)
PostgreSQL's standard SQL function "extract()" will operate on timestamps, but a) "date" isn't a valid argument to extract(), and b) it returns subfields, not a collection of subfields. Conceptually, a date consists of a collection of three subfields: year, month, and day.
select extract(year from current_timestamp),
extract(month from current_timestamp),
extract(day from current_timestamp),
-- Concatenate and cast to type "date".
(extract(year from current_timestamp) || '-' ||
extract(month from current_timestamp) || '-' ||
extract(day from current_timestamp))::date

Finding previous day of the week

In PostgreSQL 8.4, given a date, if that date is not a Friday, I would like to find the date of the previous Friday. Can someone tell me if there is an inbuilt function or give the logic behind getting my own function.
Try this, works on other days too, blog about it http://www.ienablemuch.com/2010/12/finding-previous-day-of-week.html
create or replace function previous_date_of_day(the_date date, dow int) returns date
as
$$
select
case when extract(dow from $1) < $2 then
$1 - ( extract(dow from $1) + (7 - $2) )::int
else
$1 - ( extract(dow from $1) - $2)::int
end;
$$ language 'sql';
select to_char(z.ds, 'Mon dd yyyy dy') as source,
to_char( previous_date_of_day(z.ds, 5), 'Mon dd yyyy dy') as dest
from
(
select 'Dec 1 2010'::date + x.n as ds
from generate_series(0,17) as x(n)
) as z
You solve it without using case:
select
the_date
from
(
select
now()::date - num as the_date, -- generate rows of possible dates
extract(dow from (now()::date - num)) -- dow for the where condition
from (select generate_series(0,6) as num) as t
) as days
where date_part = 5;
SELECT
CASE
-- 1. if Friday, return date
WHEN EXTRACT(DOW FROM my_date) = 5
THEN my_date
-- 2. if Saturday, subtract 1
WHEN EXTRACT(DOW FROM my_date) = 6
THEN my_date - INTERVAL '1 day'
-- 3. all other days of the week, subtract `DOW + 2` from my_date
-- should be ELSE for future-proofing ;-) MB
ELSE -- WHEN EXTRACT(DOW FROM my_date) < 5 THEN
my_date - ((EXTRACT(DOW FROM my_date) + 2)::TEXT||'days')::INTERVAL
END AS tgif
FROM
my_table
WHERE
my_date IS NOT NULL
select case when extract(dow from your_date) < 5 then
your_date - (extract(dow from your_date) + integer '2')
else when extract(dow from your_date) > 5 then
your_date - integer '1'
else
your_date
end
Reference http://developer.postgresql.org/pgdocs/postgres/functions-datetime.html