Trying to display last month data from SQL database - where clause - sql

I am using a where clause to run a query in a system.
The below where clause works when I want to look at data changed in the last 7 days. But I now need to find data changed last month. I do not want last 30 days as I need to have this run each month.
changedate >= dateadd(day,-7,getdate())
Please help? By "Last Month" I mean the previous months data. For example if the report is run on the 5th of July, the data displays results from 1st June - 30th June.

Presumably, you want:
changedate >= dateadd(month, -1, getdate())
EDIT:
If you want the previous complete month:
changedate < datefromparts(year(getdate()), month(getdate()), 1) and
changedate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
Or, if you don't care about optimizing the query (because this prevents the use of partitions):
datediff(month, changedate, getdate()) = 1

maybe
changedate between DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) and EOMONTH(GETDATE(),-1)
or
month(changedate) = month(getdate()) -1
and year(changedate) = year(getdate())

Related

Getting all data from last month

I am building an SQL view which shows me all entries of table T where the information is last month. I want it so that if I run the view any time in August, it will show me all entries for July, not just a month before which is what I have done with my current code.
Please see this:
where cast(t.Ticket_OpenDate as date) >= cast(dateadd(month, -1, getdate()) as date)
I look forward to hearing from someone.
Using DATEDIFF as in the other answer will not perform well because it cannot use indexes (it is not sarge-able).
It is much better to use a date interval (start and end), in this case we want a half-open interval (exclusive end date):
WHERE t.Ticket_OpenDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) - 1, 1)
AND t.Ticket_OpenDate < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) , 1)
You should be able to use the DATEDIFF() function for that:
WHERE DATEDIFF(month, CAST(t.Ticket_OpenDate as date), GETDATE()) = 1
See db<>fiddle for an example.

SQL get previous month (in January too)

Hello I'm looking for simple way, how to get data from previous month. I get this code but it didn't work in January (result is 12 2021 and I need 12 2020)
select month(dateadd(month,-1,getdate())), year(getdate())
Presumably, you have some sort of date column.
In SQL Server, you can express this concept using datediff():
where datediff(month, datecol, getdate()) = 1
However, that is not "sargable", meaning that it prevents the use of indexes. So, I would instead recommend:
where datecol < datefromparts(year(getdate()), month(getdate()), 1) and
datecol >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))
If you simply want the first day of the previous month, you can use:
dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))
Try This
select CASE WHEN month(getdate())>1 THEN month(getdate())-1 ELSE 12 END ,
CASE WHEN month(getdate())>1 THEN YEAR (getdate()) ELSE YEAR (getdate()) -1 END
Using the answer given here: How can I select the first day of a month in SQL?
SELECT dateadd(month,-1,DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as previousmonth;
output:
2020-12-01 00:00:00.000
I can provide next query using FORMAT function:
SELECT
-- get current day in previous month
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-dd') as current_previousmonth,
-- get first of previous month
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-01') as first_previousmonth,
-- previous month without date
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM') as previousmonth;
test T-SQL here
Here you go!
select dateadd(mm,-1,eomonth(getdate())) as [Previous Month]
Result:
Previous Month
--------------
2020-12-31
You could also use CONVERT() or FORMAT() functions to format the date as you desire.
Try
SELECT FORMAT(DATEADD(month, -1, GETDATE()),'MM/yyyy');
It will give you previous month and the year. If you are comparing to a date column in a existing table, then you need the date part too as you want to know December of which year was the previous month. But if you don't want the year, then just adjust the 'MM/yyyy' part to suit your purpose.

How I can fetch last two full years and current year records in SQL Server

I have following expression in my where clause:
DA.Access_Date >= DATEADD(YEAR, -2, GETDATE())
But it returns data till '2015-02-17' i.e. current year minus two.
I want data of two full years and current year
e.g. 2015-01-01 to till date. Any inputs on this will be appreciated.
Try this : Here DATEADD(yy, DATEDIFF(yy,0,getdate()) will give start month of the year
DA.Access_Date >= DATEADD(YEAR, -2, DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0))
With the help of YEAR scalar function
WHERE
YEAR(DA.Access_Date) in (YEAR(GETDATE()),YEAR(GETDATE())-1,YEAR(GETDATE())-2)
Your condition should be like below. DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0) this will returns first day of 2015 year.
DA.Access_Date >= DATEADD(YEAR,DATEDIFF(YEAR, 0, GETDATE())-2,0)
Just compare the year.
Try
YEAR(DA.Access_Date) >= (YEAR(GETDATE()) - 2)
You should try this in where condition.
Year(DA.Access_Date) >= Year(getdate()) - 2

SQL getdate issue with month

i need help on my little problem.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
WHERE Day(ServiceDate) BETWEEN '1' AND Day(getdate() -2)
AND Month(ServiceDate) =
CASE
WHEN Day(getdate()) <=2
THEN Month(getdate() -1
ELSE Month(getdate())
END
AND Year(ServiceDate) = Year(getdate())
Now the problem is the first and the second of the Month.
The query don't use the last month. It shows the actual month.
I hope its clear what i need.
if we have the 01-06-2016 and i need minus 2, so the query must give me back to the day 30-05-2016
big THX
the output for today with this query
output query
Assuming you are using sql-server, you need to use DATEADD(Day, -2, GETDATE()) for subtracting 2 days from current date.
I think I understand the logic now:
If the current day is the 1st of the month, get all the records from the start of previous month, until 2 days before it ends.
If the current day is the 2nd of the month, get all the records from the start of the previous month until one day before it ends.
If the current day is the 3rd of the month or higher, get all the records from the beginning of the current month until 2 days ago.
Since you are using the FORMAT() function that was introduced in 2012 version, you can also use the EOMONTH() function that was introduced in the same version.
This function returns the date of the end of the month of the date it receives as an argument, and also have a useful optional second argument that specifies the numbers of months to add to the date passed to the function.
Using this function will allow you to write your query without using any functions on the ServiceDate column, thus enabling the use of any indexes defined on this column.
DECLARE #Now datetime = GETDATE()
SELECT FORMAT(ServiceDate, 'dd-MM-yyy') AS ServiceDate
FROM Services
WHERE (
DAY(#Now) <= 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -2))
AND ServiceDate < DATEADD(DAY, -(DAY(#Now)-1), EOMONTH(#Now, -1))
)
OR
(
DAY(GETDATE()) > 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -1))
AND ServiceDate < DATEADD(DAY, -2, #Now)
)
Compute enddate as 2 days before getdate() and select data in interval from enddate's first of month and enddate.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
CROSS APPLY (SELECT enddate = DATEADD(D,-2,getdate()) x
WHERE ServiceDate BETWEEN DATEADD(MONTH,DATEDIFF(MONTH,0,x.enddate),0) AND x.enddate

Keyword for "Last Month" in SQL Server 2008

I have a query (pasted below), and I would like to make it so that people don't need to update the completed date range. I would like for it to automatically just get results from last month. So if it is run in February, for example, it will give me results for all completed items that meet my criteria for January. Can anyone think of a way to do that?
select External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c, Completed_Date__C,
COUNT(External_ID__c)
from Business_Solutions_D.dbo.Reporting_SalesForce_AspireBaseData
where PIF_Branch_Code = 977
and Completed_Date__C >= '2015-01-01'
and Completed_Date__C < '2015-02-01'
and Delete_Flag__C = 'FALSE'
group by External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c,
Completed_Date__C
There is no "keyword" for last month. You have to put that in your predicates.
Here is an example of how to get some date values for this.
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()), 0) as BeginningOfThisMonth
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()) - 1, 0) as BeginningOfPreviousMonth
If you want to see a number of other date routines here is an excellent blog post with quite a few of them. http://www.sqlservercentral.com/blogs/lynnpettis/2009/03/25/some-common-date-routines/
If you mean the last month prior to this one, you can do it in two steps: first, find the first day of the current month
#firstDayOfThisMonth = DATEADD(day, DAY(GETDATE())-1, GETDATE())
then subtract one month:
#firstDayOfLastMonth = DATEADD(month, -1, #firstDayOfThisMonth)
Then your query would be:
and Completed_Date__C >= #firstDayOfLastMonth
and Completed_Date__C < #firstDayOfThisMonth
Another way would be to query where the difference (in months) between Completed_Date__C and the current date is 1:
and DATEDIFF(Completed_Date__C, GETDATE()) = 1
You can do this with date arithmetic. One trick to get the first date of the month is to subtract the current day of the month from the date and add one day. SQL Server allows you to do this with + and - instead of dateadd(), on a datetime value. Of course, you need to remove the time component as well (using cast( as date)).
The logic looks like this for the current month:
where Completed_Date__C >= cast(getdate() - day(getdate()) + 1 as date) and
Completed_Date__C < dateadd(month, 1, cast(getdate() - day(getdate()) + 1 as date))
And like this for the previous month:
where Completed_Date__C >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
Completed_Date__C < cast(getdate() - day(getdate()) + 1 as date)
This has the nice property that it is a sargeable as your original code, so it will take advantage of an index on the column, if appropriate.
You just need to have it do some date math to calculate it.
--Go to last day of prev month - 'Day' to account for varying month day counts
and Completed_Date__C >= GETDATE() - DATEPART(DAY, GETDATE()) - DATEPART(DAY, GETDATE() - DATEPART(DAY, GETDATE())) + 1
and Completed_Date__C < GETDATE() - DATEPART(DAY, GETDATE()) + 1
When you do additions on DateTimes + integer it assumes it day based addition.