How to fix a datetime restriction problem in a sql query? - sql

I'm developing a SQL Query, as a restriction, I want that the query returns data from the first day of the last month until now.
For example: If the query is executed today, the query will only return data entered from 01/03/2019 until today.
To do this, i created the following restriction:
...
SF1010.F1_DTDIGIT>=concat(YEAR(GETDATE()),'0',month(GETDATE())-1,'01') AND
...
The problem is in the months 01, 11 and 12:
If the month is "11", the algorithm will return "1901001" and not "191001".
If the month is "01", the algorithm will return "190001" and not "181201".
Thanks for any help.

SF1010.F1_DTDIGT BETWEEN $yourDate AND date_add($yourDate,interval -DAY($yourDate)+1 DAY)
This gets dates between your date and the first day of the month. first day logic works by subtracting the DAY part to get first of month.

This query will do the comparison of your DTDIGIT with the first day of the previous month in the DATE format:
SF1010.F1_DTDIGIT >= STR_TO_DATE(CONCAT(YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH)),'-',MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)),'-','1'), '%Y-%m-%d')
Explanation
DATE_SUB(NOW(), INTERVAL 1 MONTH) returns the date exactly one month ago. We use that date to get the previous month
YEAR() and MONTH() functions use the date explained above
STR_TO_DATE() function converts a string representing a date to the
MySQL DATE format, using the mask (in this example, it's
'%Y-%m-%d').

How about this?
SF1010.F1_DTDIGT >= date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval -1 month)
This assumes the date is not in the future. You can add another condition if that is possible.
If you happen to be using SQL Server, you can do this weird form of date arithmetic:
SF1010.F1_DTDIGT >= dateadd(month, datediff(month, 0, getdate()) - 1, 0)

Related

How to get the first day of the previous month in SQL (BigQuery)

Would any of you know and would like to share the konwledge how to subtract the number of days from the current date (the data is type = DATE) so that I get the first day of the previous month. Here is an example:
Current Date = '2022-10-27'
The date I want = '2022-09-01'
I know how to get the first day of the current month using this:
(CURRENT_DATE() - EXTRACT(DAY FROM CURRENT_DATE()) +1)
BuT I have no idea how to check how many days there were in the previous month and hence get the correct answer.
I though that maybe DATE_TRUNC(CURRENT_DATE() - EXTRACT(DAY FROM CURRENT_DATE())) would work but I'm getting this error:
"No matching signature for function DATE_TRUNC for argument types: DATE"
SO that's clearly not the way. Any suggestions please? :)
Try using a combination of DATE_TRUNC and DATE_SUB as follows:
select current_date() as curr_date,
date_sub(date_trunc(current_date(), MONTH), INTERVAL 1 MONTH) as lm_day_1
It produces the following:

how to get data for last calender week in redshift

I have a below query that I run to extract material movements from the last 7 days.
Purpose is to get the data for the last calender week for certain reports.
select
*
From
redshift
where
posting_date between CURRENT_DATE - 7 and CURRENT_DATE - 1
That means I need to run the query on every Monday to get the data for the former week.
Sometimes I am too busy on Monday or its vacation/bank holiday. In that case I would need to change the query or pull the data via SAP.
Question:
Is there a function for redshift that pulls out the data for the last calender week regardless when I run the query?
I already found following solution
SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)
But this doesnt seem to be working for redshift sql
Thanks a lot for your help.
Redshift offers a DATE_TRUNC('week', datestamp) function. Given any datestamp value, either a date or datetime, it gives back the date of the preceding Sunday.
So this might work for you. It filters rows from the Sunday before last, up until but not including, the last Sunday, and so gets a full week.
SELECT id
FROM table1
WHERE date >= DATE_TRUNC('week', NOW()) - INTERVAL 1 WEEK
AND date < DATE_TRUNC('week', NOW())
Pro tip: Every minute you spend learning your DBMS's date/time functions will save you an hour in programming.

Date Functions Trunc (SysDate)

I am running the below query to get data recorded in the past 24 hours. I need the same data recorded starting midnight (DATE > 12:00 AM) and also data recorded starting beginning of the month. Not sure if using between will work or if there is better option. Any suggestions.
SELECT COUNT(NUM)
FROM TABLE
WHERE
STATUS = 'CNLD'
AND
TRUNC(TO_DATE('1970-01-01','YYYY-MM-DD') + OPEN_DATE/86400) = trunc(sysdate)
Output (Just need Count). OPEN_DATE Data Type is NUMBER. the output below displays count in last 24 hours. I need the count beginning midnight and another count starting beginning of the month.
The query you've shown will get the count of rows where OPEN_DATE is an 'epoch date' number representing time after midnight this morning*. The condition:
TRUNC(TO_DATE('1970-01-01','YYYY-MM-DD') + OPEN_DATE/86400) = trunc(sysdate)
requires every OPEN_DATE value in your table (or at least all those for CNLD rows) to be converted from a number to an actual date, which is going to be doing a lot more work than necessary, and would stop a standard index against that column being used. It could be rewritten as:
OPEN_DATE >= (trunc(sysdate) - date '1970-01-01') * 86400
which converts midnight this morning to its epoch equivalent, once, and compares all the numbers against that value; using an index if there is one and the optimiser thinks it's appropriate.
To get everything since the start of the month you could just change the default behaviour of trunc(), which is to truncate to the 'DD' element, to truncate to the start of the month instead:
OPEN_DATE >= (trunc(sysdate, 'MM') - date '1970-01-01') * 86400
And the the last 24 hours, subtract a day from the current time instead of truncating it:
OPEN_DATE >= ((sysdate - 1) - date '1970-01-01') * 86400
db<>fiddle with some made-up data to get 72 back for today, more for the last 24 hours, and more still for the whole month.
Based on your current query I'm assuming there won't be any future-dated values, so you don't need to worry about an upper bound for any of these.
*Ignoring leap seconds...
It sounds like you have a column that is of data type TIMESTAMP and you only want to select rows where that TIMESTAMP indicates that it is today's date? And as a related problem, you want to find those that are the current month, based on some system values like CURRENT TIMESTAMP and CURRENT DATE? If so, let's call your column TRANSACTION_TIMESTAMP instead of (reserved word) DATE. Your first query could be:
SELECT COUNT(NUM)
FROM TABLE
WHERE
STATUS = 'CLND'
AND
DATE(TRANSACTION_TIMESTAMP)=CURRENT DATE
The second example of finding all for the current month up to today's date could be:
SELECT COUNT(NUM)
FROM TABLE
WHERE
STATUS = 'CLND'
AND
YEAR(DATE(TRANSACTION_TIMESTAMP)=YEAR(CURRENT DATE) AND
MONTH(DATE(TRANSACTION_TIMESTAMP)=MONTH(CURRENT DATE) AND
DAY(DATE(TRANSACTION_TIMESTAMP)<=DAY(CURRENT DATE)

How to decipher complex DATEADD function from MS Access

I have inherited a query from an old MS Access DB and cannot for the life of me figure out what was trying to be done in this date parameter function. I normally only use SQL and this seems a bit different. Can any one assist in describing what this logic is doing?
use pdx_sap_user
go
select po_number,
po_issue_date
from vw_po_header
where po_issue_date > getDate() And PO_issue_date < DateAdd("d",-1,DateAdd("m",8,DateAdd("d",-(Day(getDate())-1),getDate())))
You can de-obfuscate it a lot by using DateSerial:
where
po_issue_date > getDate() And
po_issue_date < DateSerial(Year(getDate()), Month(getDate()) + 8, 0)
First: there is no getDate() function in Access. Probably it should be Date() which returns the current date.
Now starting from the inner expression:
Day(Date()) returns the current day as an integer 1-31.
So in DateAdd("d", -(Day(Date())-1), Date()) from the current date are subtracted as many days as needed to return the 1st of the current month.
Then:
DateAdd("m", 8, DateAdd("d", -(Day(Date())-1), Date()))
adds 8 months to the the 1st of the current month returning the 1st of the month of the date after 8 months.
Finally:
DateAdd("d", -1,...)
subtracts 1 day from the date returned by the previous expression, returning the last day of the previous month of that date.
So if you run today 13-Sep-2019 this code, the result will be:
30-Apr-2020
because this is the last day of the previous month after 8 months.
I think the following:
Take the current date
Substract the current day of month -1 to get the first day of current month
Add 8 month to this
Substract 1 day to get the last day of the previous month
So it calculates some deadline in approx 8 months.
But I wonder how a PO issue date can be in the future...

Selecting the first day of the month in HIVE

I am using Hive (which is similar to SQL, but the syntax can be little different for the SQL users). I have looked at the other stackoverflow, but they seems to be in the SQL with different syntax.
I am trying to the get the first day of the month through this query. This one gives me today's day. For example, if today is 2015-04-30, then result would be 2015-04-01. Thanks!
select
cust_id,
FROM_UNIXTIME(UNIX_TIMESTAMP(),'yyyy-MM-dd') as first_day_of_month_transaction
--DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as first_day_of_month_transaction --SQL format. Not compatible in Hive.
from
customers;
Try this
date_format(current_date,'yyyy-MM-01')
To get the first day of the month, you can use:
date_add(<date>,
1 - day(<date>) )
Applied to your expression:
date_add(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd'),
1 - day(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd'))
)
But this will work for any column in the right format.
SELECT TRUNC(rpt.statement_date,'MM') will give you the first day of month.
You can use this query to calculate the First day of the current month
Select date_add(last_day(add_months(current_date, -1)),1);
Instead of current_date, you can use the date field name.
last_day => Gives the last day of current month
add_months with -1 => Gives previous month
date_add with 1 => Add one day
Another way - select concat(substring(current_date,1,7),'-01');