PostgreSQL: Date Calendar Days Interval Scenario - postgresql

I would like to print this table (displaying only 4 rows for brevity):
Dates
Period
01-MAR-2022
61
02-MAR-2022
61
03-MAR-2022
61
30-APR-2022
61
So far I have:
SELECT CAST(TRUNC(date_trunc('month',CURRENT_DATE) + interval '-2 month') AS DATE) + (n || 'day')::INTERVAL AS Dates
, date_trunc('month',CURRENT_DATE) + interval '-2 month' + INTERVAL '2 month' - date_trunc('month',CURRENT_DATE) + interval '-2 month' AS Period
FROM generate_series(0,61) n
Please help with a better way of generating the period and also replacing the hard-coded 61 in generate_series(0,61).
Thanks!

What are you actually trying to accomplish, it is not clear nor specified. BTW your query is invalid. It appears you looking to list each data from first date of 2 months prior to the last date of 1 month prior and the total number of days in that range. The following would give the first date, and using date subtraction gives the number of days.
with full_range( first_dt, num_days) as
( select date_trunc ('month', (current_date - interval '2 months'))::date
, date_trunc ('month', (current_date - interval '1 day'))::date -
date_trunc ('month', (current_date - interval '2 months'))::date
)
select *
from full_range;
With that in hand you can use the num_days with generate series with the expression
select generate_series(0, num_days-1) from full_range
Finally combine the above arriving at: (see demo)
with full_range( first_dt, num_days) as
( select date_trunc ('month', (current_date - interval '2 months'))::date
, date_trunc ('month', (current_date - interval '1 day'))::date -
date_trunc ('month', (current_date - interval '2 months'))::date
)
select (first_dt + n*interval '1 day')::date, num_days
from full_range
cross join (select generate_series(0, num_days-1) from full_range) gn(n);

Related

oracle Level column to postgres conversion

I have an oracle query to change it into postgres
SELECT cast(to_char(ADD_MONTHS(TRUNC(ADD_MONTHS(SYSDATE, -6),'MM'),LEVEL - 1),'MMYYYY') as number) monthid,
to_char (ADD_MONTHS(TRUNC(ADD_MONTHS(SYSDATE, -6),'MM'), LEVEL - 1),'MON-YYYY') monthdesc
From dual
CONNECT BY LEVEL <= MONTHS_ BETWEEN (SYSDATE, ADD_MONTHS (SYSDATE, -6)) + 1;
I tried with CTE and generate_series, but stuck somewhere to get result set
---------------------
MONTHID MONTHDESC
---------------------
172022 JUL-2022
82022 AUG-2022
92022 SEP-2022
102022 OCT-2022
112022 NOV-2022
122022 DEC-2022
12023 JAN-2023
This will generate a list of the last six months:
select to_char(g.dt, 'mmyyyy') as monthid,
to_char(g.dt, 'MON-yyyy') as monthdesc
from generate_series(date_trunc('month', current_date) - interval '6 month',
date_trunc('month', current_date), interval '1 month') as g(dt)
However this will return 072022 for July 2022, not 172022 as in your sample data.

Postgresql - query to get difference in data count

I have two tables, today's_table and yeterday's_table.
I need to compare the data for an interval of 15 mins at exact same times for today and yesterday.
For example, for below data let's I need to check from 00:00:00 and 00:15:00 on 20201202 and 20201202. So difference should come out as '3' since the yesterday's_table has 8 records and today's_table has 5 records.
today's_table:
Yesterday's table:
I tried something like; (consider now() is 00:15:00)
select count(*) from yeterday's_table where time between now() - interval "24 hours" and now() - interval "23 hours 45 mins"
minus
select count(*) from today's_table where time = now() - interval "15 minutes";
is there any other way to do this?
You can easily do this with subqueries:
SELECT b.c - a.c
FROM (select count(*) as c from yeterdays_table where time between now() - interval '24 hours' and now() - interval '23 hours 45 mins') a,
(select count(*) as c from todays_table where time = now() - interval '15 minutes') b;
Bear in mind you need to single-quote your intervals, and your table names cannot have quotes in them.

How to calculate how many intervals at given daterange? simpler version

I can write:
select count(*) from generate_series(
'2019-03-01'::date, '2019-05-01'::date,
interval '3 day 1 hour'
)
-- exclude upper boundary
where generate_series <> date '2019-05-01'::date;
Is there a way to do it simpler? like:
daterange( '2019-03-01', '2019-05-01' ) / interval '3 day 1 hour'
You can use
EXTRACT(epoch FROM some_interval)
to get an interval's duration in seconds.
You could use that as follows:
SELECT EXTRACT(epoch FROM '2019-05-01'::timestamptz - '2019-03-01'::timestamptz)
/ EXTRACT(epoch FROM interval '3 day 1 hour');
Note that this will only give correct answers for intervals that are measured in days or lesser units; for months and more you have to go with your original solution.

Compare day in current month to same day previous month PostgreSQL

I'm trying to compare values of current month's data to previous months using PostgreSQL. So if today is 4/23/2018, I want the data for 3/23/2018.
I've tried current_date - interval '1 month' but it is problematic for months with 31 days.
My table is structured as simply as
date, value
Check this example query:
WITH dates AS (SELECT date::date FROM generate_series('2018-01-01'::date, '2018-12-31'::date, INTERVAL '1 day') AS date)
SELECT
start_dates.date AS start_date,
end_dates.date AS end_date
FROM
dates AS start_dates
RIGHT JOIN dates AS end_dates
ON ( start_dates.date + interval '1 month' = end_dates.date AND
end_dates.date - interval '1 month' = start_dates.date);
It will output all end_dates and corresponding start_dates. The corresponding dates are defined by interval '1 month' and checked in both ways:
start_dates.date + interval '1 month' = end_dates.date AND
end_dates.date - interval '1 month' = start_dates.date
The output looks like this:
....
2018-02-26 2018-03-26
2018-02-27 2018-03-27
2018-02-28 2018-03-28
2018-03-29
2018-03-30
2018-03-31
2018-03-01 2018-04-01
2018-03-02 2018-04-02
2018-03-03 2018-04-03
2018-03-04 2018-04-04
....
Note, that there are 'gaps' for days without corresponding dates.
Back to your table, join the table with itself (giving aliases) and use given join condition, so the query would look like this:
SELECT
start_dates.value - end_dates.value AS change,
start_dates.date AS start_date,
end_dates.date AS end_date
FROM
_your_table_name_ AS start_dates
RIGHT JOIN _your_table_name_ AS end_dates
ON ( start_dates.date + interval '1 month' = end_dates.date AND
end_dates.date - interval '1 month' = start_dates.date);
Given the following table structure:
create table t (
d date,
v int
);
After populating with some dates and values, there is a way to find the value of the previous month using simple calculations and the LAG function, without resorting to joins. I am not sure how it compares from a performance perspective, so please run your own tests before selecting which solution to use.
select
*,
lag(v, day_of_month) over (order by d) as v_end_of_last_month,
lag(v, last_day_of_previous_month + day_of_month - cast(extract(day from d - interval '1 month') as int)) over (order by d) as v_same_day_last_month
from (
select
*,
lag(day_of_month, day_of_month) over (order by d) as last_day_of_previous_month
from (
select
*,
cast(extract(day from d) as int) as day_of_month
from
t
) t_dom
) t_dom_ldopm;
You may note that between the 29th and 31st of March, the comparison will be made against the 28th of February, since the same day does not exist in February for those particular dates. The same logic applies to other months with different number of days.

get last three month records from table

How to get last 3 months records from the table.
SELECT *
from table
where month > CURRENT_DATE-120
and month < CURRENT_DATE
order by month;
I have used the above query is it correct? shall I use this for get last 3 month record from the table.
You can use built-in INTERVAL instruction
Check how this works:
SELECT CURRENT_DATE - INTERVAL '3 months'
and you can rewrite your SQL to:
SELECT * from table where date > CURRENT_DATE - INTERVAL '3 months'
(not checked but this should give you an idea how to use INTERVAL instruction)
Try that:
SELECT *
FROM table
WHERE month BETWEEN EXTRACT(MONTH FROM NOW() - INTERVAL '3 months')
AND EXTRACT(MONTH FROM NOW())
ORDER BY month
;
This filters the last 3 calendar months
SELECT * from table where date >= to_char(CURRENT_DATE - INTERVAL '3 months', 'YYYY-MM-01')::date
select date::date
from generate_series((current_date - INTERVAL '1 Month')::date, (current_date - INTERVAL '1 DAY')::date,'1
day'::interval) date
WHERE date >= date_trunc('month', current_date - interval '3' month)
and date < date_trunc('month', current_date)
This will give last three months date list, excluding current months date. Example if current month is November. This list will give use all dates of August, Septemeber and October.