PostgreSQL query to return the set of days between two dates - sql

I need to return the dates between the 05 of the last month and the 05 of the current month Example today is the 16/08/2022 I recuperate therefore the whole of the days between the 05/07/2022 and the 05/08/2022
For the moment I try with this query
SELECT DATE from Db_name where date between date_trunc('month', current_date-1) and date_trunc('month',current_date)

Your initial query is very much on track. Just a couple additional things about dates:
current_date-1 subtracts 1 day, you need to subtract 1 month. Thus current_date - interval '1 month'.
date_trunc(somedate) returns the 1st of the month so
date_trunc('2022-08-17') returns 2022-08-01.
getting to the 5th of the month from the 1st just add interval '4 days'.
adding or subtracting intervals to dates results in timestamps.
Since you want dates so needs to be cast back to date.
select *
from db_name
where some_date between (date_trunc('month', current_date-interval '1 month') + interval '4 days')::date
and (date_trunc('month', current_date) + interval '4 days')::date;
But I will repeat do not any reserved word or data type as a name. At best is causes confusion, at worst it will run but do the wrong thing.

Related

Return first date (Sunday) of a particular week in SQL redshift

I am trying to set a WHERE filter where only results with dates after last week Sunday (including last week Sunday) are returned. What I have at the moment is:
date_part(w,GETDATE())
This gives me the current week number. How do I know find the first date of this week number (43) so the 18th of October?
Hmmm . . . This returns weeks starting on Mondays, which is pretty standard:
date_trunc('week', current_date)
If you want Sunday to start the week, then:
date_trunc('week', current_date + interval '1 day') - interval '1 day'
Note: If today is Sunday, then it returns today's date. If you want last Sunday's date in that case, just use:
date_trunc('week', current_date) - interval '1 day'

postgresql query to return the day of the week of the first day of the month two years from today

I used postgresql to solve the quesion, query to return the day of the week of the first day of the month two years from today. I was able to solve it with the query below, but I am not sure my query is correct, I just wanna make sure
select cast(date_trunc('month', current_date + interval '2 years') as date)
You are correctly computing the first day of the month two years later with:
date_trunc('month', current_date + interval '2 years')
If you want the corresponding day of the week, you can use extract();
extract(dow from date_trunc('month', current_date + interval '2 years'))
This gives you an integer value between 0 (Sunday) and 6 (Saturday)

Get average for "last month" only

Pretty new to SQL and have hit a roadblock.
I have this query, which works fine:
SELECT
(COUNT(*)::float / (current_date - '2017-05-17'::date)) AS "avg_per_day"
FROM "table" tb;
I now want it to include only data from the last month, not all time.
I've tried doing something along the lines of:
SELECT
(COUNT(*)::float / (current_date - (current_date - '1 month' ::date)) AS "avg_per_day"
FROM "table" tb;
The syntax is clearly wrong, but I am not sure what the right answer is. Have googled around and tried various options to no avail.
I can't use a simple AVG because the number I require is an AVG per day for the last month of data. Thus I've done a count of rows divided by the number of days since the first occurrence to get my AVG per day.
I have a column which tells me the date of the occurrence, however there are multiple rows with the same date in the dataset. e.g.
created_at
----------------------------
Monday 27th June 2017 12:00
Monday 27th June 2017 13:00
Tuesday 28th June 2017 12:00
and so on.
I am counting the number of occurrences per day and then need to work out an average from that, for the last month of results only (they date back to May).
The answer depends on the exact definition of "last month" and the exact definition of "average count".
Assuming:
Your column is defined created_at timestamptz NOT NULL
You want the average number of rows per day - days without any rows count as 0.
Cover 30 days exactly, excluding today.
SELECT round(count(*)::numeric / 30, 2) -- simple now with a fixed number of days
FROM tbl
WHERE created_at >= (now()::date - 30)
AND created_at < now()::date -- excl. today
Rounding is optional, but you need numeric instead of float to use round() this way.
Not including the current day ("today"), which is ongoing and may result in a lower, misleading average.
If "last month" is supposed to mean something else, you need to define it exactly. Months have between 28 and 31 days, this can mean various things. And since you obviously operate with timestamp or timestamptz, not date, you also need to be aware of possible implications of the time of day and the current time zone. The cast to date (or the definition of "day" in general) depends on your current timezone setting while operating with timestamptz.
Related:
Ignoring timezones altogether in Rails and PostgreSQL
Select today's (since midnight) timestamps only
Subtract hours from the now() function
I think you just need a where clause:
SELECT
(COUNT(*)::float / (current_date - (current_date - '1 month' ::date)) AS "avg_per_day"
FROM "table" tb
WHERE created_at > (current_date - '1 month' ::date)
I believe Postgresql and other RDBMS has AVG() to calculate average.
SELECT AVG(tb.columnName) AS avg_per_month
FROM someTable tb
WHERE
tb.createdDate >= [start date of month] AND
tb.createdDate <= [end date of month]
Edit: I subtract current date with INTERVAL. I am on mobile phone so I cannot test.
SELECT
(COUNT(*)::float / (current_date - ( current_date - INTERVAL '1 month')) AS "avg_per_day"
FROM "table" tb;

Teradata SQL Same Day Prior Year in same Week

Need help figuring out how to determine if the date is the same 'day' as today in teradata. IE, today 12/1/15 Tuesday, same day last year was actually 12/2/2014 Tuesday.
I tried using current_date - INTERVAL'1'Year but it returns 12/1/2014.
You can do this with a bit of math if you can convert your current date's "Day of the week" to a number, and the previous year's "Day of the week" to a number.
In order to do this in Teradata your best bet is to utilize the sys_calendar.calendar table. Specifically the day_of_week column. Although there are other ways to do it.
Furthermore, instead of using CURRENT_DATE - INTERVAL '1' YEAR, it's a good idea to use ADD_MONTHS(CURRENT_DATE, -12) since INTERVAL arithmetic will fail on 2012-02-29 and other Feb 29th leap year dates.
So, putting it together you get what you need with:
SELECT
ADD_MONTHS(CURRENT_DATE, -12)
+
(
(SELECT day_of_week FROM sys_calendar.calendar WHERE calendar_date = CURRENT_DATE)
-
(SELECT day_of_week FROM sys_calendar.calendar WHERE calendar_date = ADD_MONTHS(CURRENT_DATE, -12))
)
This is basically saying: Take the current dates day of week number (3) and subtract from it last years day of week number (2) to get 1. Add that to last year's date and you'll have the same day of the week as current date.
I tested this for all dates between 01/01/2010 and CURRENT_DATE and it worked as expected.
Why don't you simply subtract 52 weeks?
current_date - 364
The SQL below will get you to the abbreviated name for the day of week, it's cumbersome but it works across versions of Teradata.
SELECT CAST(CAST(ADD_MONTHS(CURRENT_DATE, -12) AS DATE FORMAT 'E3') AS CHAR(3)) AS LY_DayOfWeek
, CAST(CAST(CURRENT_DATE) AS DATE FORMAT 'E3') AS CHAR(3)) AS CY_DayOfWeek
Dates are internally represented at integers in Teradata as (Year-1900) * 100000 + (MONTH * 100) + DAY. You may be able to do some creative arithmetic to figure out that 12/1/2015 Tuesday was 12/2/2014 Tuesday last year.

SQL Count days till first of the month

How would I count the days from a date till the first of the following month
Example:
--Start Date
07-07-2011
How many days till:
-- The 1st of the succeeding month of the start date above
08-01-2011
Expected Result (in days):
25
So if I counted the day I get 25, so running this query gets me the desired timestamp:
SELECT CURRENT_DATE + INTERVAL '25 DAYS'
Results:
2011-08-01 00:00:00
just can't think of a way to get the number of days, any suggestions?
Or start date, end date, number of days between?
I don't have a PostgreSQL server handy, so this is untested, but I would try:
SELECT (DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 MONTH') - CURRENT_DATE