SQL server - Select all items with a date on the previous month - sql

I have a table in my SQL Server database called "items" which has a column called "dateFinished".
I have a script that will run on the 1st day of each month which needs to select all items that finished in the previous month.
So, for example, on the 1st February it will need to select all items where the dateFinished is greater than or equal to 00:00 on the 1st of January and less than 00:00 on 1st February.
it also needs to work across new years (e.g. DEC - JAN).
Any ideas?

Select *
from items
where datefinished >= dateadd(m, datediff(m, 0, GETDATE()) - 1, 0)
AND datefinished < dateadd(m, datediff(m, 0, GETDATE()), 0)

You could get a day of the previous month with dateadd(m,-1,getdate()). Then, filter on the year and month of that date in a where clause, like:
select *
from items
where datepart(yy,dateFinished) = datepart(yy,dateadd(m,-1,getdate()))
and datepart(m,dateFinished) = datepart(m,dateadd(m,-1,getdate()))
This should work across years, and also if the query is run on a later day than the first of the month.

Simple just use what I just used: DATEDIFF(mm,dateFinished,GETDATE()) = 1
SELECT *
FROM items
WHERE DATEDIFF(mm,dateFinished,GETDATE()) = 1

I would start by checking out the DATEADD function
http://msdn.microsoft.com/en-us/library/ms186819.aspx

Related

SQL SELECT SUM BETWEEN 1 Year from now to start ot the year

so I'm kinda stuck with a little query to get the SUM of the time period I want. So it already works but I want that it's automatically between 1 year from now and the beginning of the year.
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE > DATEADD (year, -1, getdate ())
AND D_INVOICEDATE < DATEADD (month , -6 ,Getdate () )
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
Currently I would have to change the query every month but I try to find a way to avoid it.
Ok. Maybe i wasn't clear enough. My problem is the -6 i have to write down. I want to switch it to a parameter that will automatically change up the date so that i get data from 01.01.2021 - 22.06.2021. So same date, but different year.
If I understand your question, you should be able to do this:
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE between DATEADD(year, -1, getdate()) AND DATEFROMPARTS(getdate(), 1, 1)
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
So instead of using where and I'm using where between. And I'm checking for todays date last year till 1st of January current year.
If you need from 1st of January previous year you can use:
between DATEFROMPARTS(year(getdate() -1), 1, 1) AND DATEADD(year, -1, getdate())

How to retrieve records that are from two months from the current date

So what I am trying to do is when I run the query, I want to return all records that were in the month two months from the current month. For example, lets say the current month is November, when the query runs, I want returned all records from September and only September. If I run the query in lets say October, I want all records from August and only August. I am trying to do this in MS SQL. Thanks for any advice.
In SQL Server, you can use:
where datecol >= dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1)) and
datecol < dateadd(month, -2, datefromparts(year(getdate()), month(getdate()), 1))
This is index- and optimizer- friendly. If you don't care about performance, you can use datediff():
where datediff(month, datecol, getdate()) = 2
This can be done in a nice 1 liner.
WHERE NOW() BETWEEN Date1 AND Date2;
You can have the month part in a variable and then it can be used in the Where clause to filter the month part of the date value is equal to the varoable value.
Query
Declare #month as int;
Set #month=datepart(month, getdate()) - 2;
Select * from yourTableName
Where month(dateCol) = #month;
The function GETDATE() can be used to retrieve the current month.
The function DATEADD(datepart,number,date) can be used to perform operations on dates. For more info look at the official docs
Thus, to retrieve the records from two months before (-2) the current month you can use the following:
DATEADD(month, -2, GETDATE())
In conclusion an example query to select all records that were in the month two months from the current month:
SELECT * FROM table
WHERE MONTH(month_column) = DATEADD(month, -2, GETDATE())
sources:
WHERE Clause to find all records in a specific month
SQL query for today's date minus two months

How to Target Last Month in SQL Query

I'm using this code in an SQL query
WHERE [Date] >= DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE()))
AND [Date] <= EOMONTH(DATEFROMPARTS(DATEPART(year,GETDATE()),DATEPART(month,GETDATE())-1,DATEPART(day,GETDATE())));
The problem is come 2020 the December query will through up an error
The code I posted manages the dates between which data will be returned. It looks at the date the code is run and choose that day from last month till the end of last month. What I need is dates from the 1st till the last day of the month prior to the one this code is called in.
I will be working on this issue tomorrow, it will be interesting to see what solutions other people can come up with.
try this
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0),
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) - 1
it will get you the previous month start and end date
If you want the previous month:
where date >= dateadd(month, -1, datefromparts(year(getdate(), month(getdate(), 1))) and
date < datefromparts(year(getdate(), month(getdate(), 1))
This simply checks that it is before the first of the this month and then subtracts a month from that.

Conditional SQL Query to fetch last date of the quarter on the basis of few condition

Basically a report is needed once a quarter, and the analysis date(any date) is the last date of the preceding quarter. So if we are loading on 10 July, “Analysis Date” would be 30 June (of the same year). HOWEVER - it is possible that the users will want to load the data early, in order to see what may need to be addressed by the end of the quarter. In that case they may want to load it on 20 June, and “Analysis Date” will still be 30 June.
How do i write the query for these two conditions, considering there will be only one month in advance for which this specific constraint is needed.
This should put you on the right track. If you have a version of SQL Server older than 2012 you will need to use something instead of EOMONTH
CREATE FUNCTION dbo.GetAnalysisDate(#date DATE)
RETURNS DATE
AS
BEGIN
IF MONTH(#date) % 3 = 0 RETURN EOMONTH(#date)
-- else
RETURN DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, #date), 0))
END
GO
-- tests
-- these should return 20181231
SELECT dbo.GetAnalysisDate('20190101')
SELECT dbo.GetAnalysisDate('20190120')
SELECT dbo.GetAnalysisDate('20190220')
-- these should return 20190331
SELECT dbo.GetAnalysisDate('20190320')
SELECT dbo.GetAnalysisDate('20190401')
SELECT dbo.GetAnalysisDate('20190420')

SQL update date to first of next month plus three months

I have this query:
update courseRights
set courseRightsLevelExpires = DATEADD(MM,3,courseRightsLevelExpires)
This works fine but what I actually need is to extend to three months from the first day of next month. For example if the rights are expiring today, May 23rd, I need to update to June 1st + 3 months.
Is it possible to do that in one query?
Update
Because it was flagged as duplicate with another question, I'm updating the content to say that I'm not only looking for the first date of next month but I need to add three months to that date.
To get the first day of next month:
DATEADD(m, DATEDIFF(m, -1, current_timestamp), 0)
Three month's after that:
DATEADD(m,3,DATEADD(m, DATEDIFF(m, -1, current_timestamp), 0))
So, if courseRightsLevelExpires holds the base date you're working from:
DATEADD(m,3,DATEADD(m, DATEDIFF(m, -1, courseRightsLevelExpires), 0))
You can use eomoth() function :
update courseRights
set courseRightsLevelExpires =
dateadd(mm, 3, dateadd(dd, 1, eomonth(courseRightsLevelExpires)));
I will do:
set nextmonthdate = last_day (your-date) + 1 day