Get last date of the previous month Transact-SQL - sql

I am trying to fetch data for the previous full month, but the data from the last day is not fetching.
Output: Previous Month is April and this condition only retrieving data up to 29th April. Data for 30th April is missing.
Can please someone help me to correct this.
OLH.DateStamp > CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0),101)
And
OLH.DateStamp < CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1),101))
Thanks in advance

The simplest way to get data for the previous month is:
DATEDIFF(month, OLH.DateStamp, GETDATE()) = 1
However, that does not use indexes. So, a better method is:
OLH.DateStamp >= DATEADD(MONTH, -1, DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))) AND
OLH.DateStamp < DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))
The expression:
DATEADD(DAY, 1 - DAY(GETDATE), CAST(GETDATE() as DATE))
returns midnight on the first day of the current month.

You should try last day of Month Should be <= OLH.Datestamp
To get Desired Output you are Looking for:
--Use It In Where Clause
DECLARE #FirstDayOfLastMonth
DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() -
2)) ), DATEADD(m, -1, GETDATE() - 1)))
,#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
OLH.DateStamp >= CONVERT(VARCHAR, #FirstDayOfLastMonth , 101) AND
OLH.DateStamp <= CONVERT(VARCHAR, #LastDayOfLastMonth , 101)

Related

SQL Code to Pull data from previous day 4am up to 3:59am current day

I am trying to pull all data for the previous day starting from 4am until 3:59am CST of the current day.
For example:
Today is 11/4/20 so I would want all data from 11/3/2020 04:00 - 11/4/2020 03:59
Can somebody help me with this? I feel like I am over thinking this and can't figure it out!
SELECT
[auth_account_number] as [Employeee ID]
,'Pearl Card Withdraw $' as [Time Off]
,tm.updated_date_time as [Date]
,[payment_amount] as [Total Time]
FROM [ig_business].[dbo].[Check_GA_Account_Charge_Detail] cd
inner join [ig_transaction].[dbo].[Transaction_Master] tm on cd.transaction_data_id=tm.transaction_data_id
where tender_dim_id='104'
and tm.updated_date_time >= convert(datetime, dateadd(day, 1, convert(date, getdate()))) + '04:00:00'
and tm.updated_date_time < convert(datetime, convert(date, getdate())) + '04:00:00'
Assuming you have a date/time column, you can use:
select t.*
from t
where dt >= convert(datetime, dateadd(day, -1, convert(date, getdate()))) + '04:00:00' and
dt < convert(datetime, convert(date, getdate())) + '04:00:00'
I was able to figure it out I used this code
and tm.updated_date_time <= dateadd(day, datediff(day, 0, getdate()), 0) + '4:00'
and tm.updated_date_time > dateadd(day, datediff(day, 0, getdate()-1), 0) + '4:00'

SQL fetch data for the present year until previous week friday

Am trying to fetch data in SQL until previous week Friday for the present year from the datetime field fetchDate
I tried something like this but it fetches until today
(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(GETDATE()))
whereas
(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(DATEADD(wk,DATEDIFF(wk,7,GETDATE()),4)))
brings me data only for the present month of the year until last week.
I believe what you need is the following:
WHERE YEAR(fetchDate) = YEAR(CURDATE())
AND fetchDate < DATE_SUB(NOW(), INTERVAL ((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7) DAY)
We get how many days ago last week's Friday was with:
((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7)
I would rather go for the following solution as it is sargable. Inside the WHERE predicate we are not wrapping the fetchdate into a function (e.g. YEAR(Fetchdate)), the query optimizer could use existing indexes and does not have to scan the whole table. Especially for BI workloads where this query is common, it is extremely important to optimize for that a lot of records are queried. It comes at the cost of little less readability
declare #tab table
(
fetchdate datetime
)
insert into #tab
values ('2019-01-01'),('2019-03-15'),('2018-12-31'),('2019-03-16')
SELECT
*,
case when datepart(weekday, getdate()) >5 then
DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end as TestLastFriday,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) as TestFirstDayOfYear
FROM #tab
where
fetchdate <= case when datepart(weekday, getdate()) >5 then DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end and
fetchdate >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)

Get data from last month in SQL Server

I checked Get the records of last month in SQL server and it did not work!
I try to get the records of last month based on my database table and column issue_date.
What's the SQL query to do this?
For clarification, today (27-April-18) I want to get all records from March-18.
I have the issue_date in the format that I convert to date but below code gives me all records from 01-March-2018 to and including today.
DATEPART(month, CONVERT (VARCHAR(11),DATEADD(day,wo_header.issue_date,`1971/12/31`),106)) = DATEPART(month, DATEADD(month, -1, getdate()))
To get firstDay and lastDay of previous month
DECLARE #FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))),
#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
SELECT #FirstDayOfLastMonth, #LastDayOfLastMonth
Your required Query
SELECT *
FROM TABLE
WHERE CAST(issue_date AS DATE) BETWEEN CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))) AND CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
Perhaps the easiest method is eomonth(). If there is no time component on issuedate:
where issuedate > eomonth(getdate(), -2) and
issuedate <= eomonth(getdate(), -1)
If there is a time component:
where issuedate >= dateadd(day, 1, cast(eomonth(getdate(), -2) as date)) and
issuedate < dateadd(day, 1, cast(eomonth(getdate(), -1) as date))
Without eomonth, I would do:
where issuedate < cast(dateadd(day, 1 - day(getdate()), getdate()) as date) and
issuedate >= dateadd(month, -1, cast(dateadd(day, 1 - day(getdate()), getdate()) as date))
The code I figured out is not pretty but it works. It first adds extra column with the month number to the SELECT portion of my code:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) As Month
And than is used for WHERE statement:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) = month(getdate())-1
So for anyone like me working in SQL report kind-of environment it should work.

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;

How do I compare against the current week using SQL Server?

How do I compare an SQL Server date column against the current week?
For instance:
WHERE [Order].SubmittedDate = *THIS WEEK*
You could convert your date to a week number and compare this to the week number from the current date. Likewise, you'll need to compare the year as well, so that you don't get last year's weeks.
WHERE DATEPART(wk, [Order].SubmittedDate) = DATEPART(wk, GETDATE())
AND DATEPART(yy, [Order].SubmittedDate) = DATEPART(yy, GETDATE())
Assuming you are meaning always "this week" and there are no records with Submitted dates in the future, which I imagine could be the case you can do:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
If dates do go into the future, the full restriction to this week is:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
AND [Order].SubmittedDate < CAST(CONVERT(VARCHAR(10), DATEADD(dd, (8 - DATEPART(dw, GETDATE())), GETDATE()), 120) AS DATETIME)
I'd strongly recommend using a clause based on a start and end date like this, as it will allow efficient index use so should perform better.
Try this:
WHERE [Order].SubmittedDate BETWEEN
DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()) AND
DATEADD(d, 7 - DATEPART(dw, GETDATE()) , GETDATE())
Maybe this can run faster, as doesn't needs to be evaluated everytime:
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()),
#EndDate = DATEADD(d, 8 - DATEPART(dw, GETDATE()) , GETDATE())
-- // Strip time part, so week starts on Sunday 00:00
SELECT #StartDate = CAST(FLOOR(CAST(#StartDate AS FLOAT)) AS DATETIME),
#EndDate = CAST(FLOOR(CAST(#EndDate AS FLOAT)) AS DATETIME)
...
WHERE [Order].SubmittedDate >= #StartDate AND [Order].SubmittedDate < #EndDate