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

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

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())

Data Preparation End OF Every Month - Moving Over 12 Months

I have data prep procedure in SQL. I want to have data preparation at the end of every month
Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.
So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.
I tried this, however, this does not give automation. Its sort of manual running end of every month
select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
into #AnalysisWindow --create temporary table #AnalysisWindow
I also tried the following, however, I’m not sure if it does for the whole month or just one day?
SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1, CAST(GETDATE() AS DATE))
Could someone pls help me/give me some suggestions.
Thanks in advance
If you want the last day of the current month, use eomonth():
WHERE DATE = CONVERT(date, EOMONTH(GETDATE()))
Note: This assumes that the date column has no time component. If that is the case:
WHERE CONVERT(date, DATE) = CONVERT(date, EOMONTH(GETDATE()))
SQL Server will still use an index (if available) even for this type of conversion.
EDIT:
To get the current months data, one method is:
WHERE DATE <= CONVERT(date, EOMONTH(GETDATE())) AND
DATE > CONVERT(date, EOMONTH(GETDATE(), -1))
The second argument to EOMONTH() is a months offset.
You can also try:
where getdate() <= EOMONTH(GETDATE()) AND
getdate() > DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
Instead of getdate(), you can use your date column.

SQL 'Round' Up a Date to a Given Day of the week

My company groups all tasks into individual weeks that end on a Thursday. Thus a task due on 3/20/19 would be grouped into the 3/21 week and tasks due on 3/22 group into the 3/28/19 week.
I'm looking to calculate this field (called duedate_Weekdue) based on an input duedate.
The following works but doesn't seem like the simplest way to do this. Anyone have more elegant methods?
Select
getdate() as duedate,
datepart(yy,getdate()) as duedate_yr,
datepart(ww,getdate()) as duedate_ww,
CASE
When datename(dw,Dateadd(day,1,getdate()))='Thursday' Then Dateadd(day,1,getdate())
When datename(dw,Dateadd(day,2,getdate()))='Thursday' Then Dateadd(day,2,getdate())
When datename(dw,Dateadd(day,3,getdate()))='Thursday' Then Dateadd(day,3,getdate())
When datename(dw,Dateadd(day,4,getdate()))='Thursday' Then Dateadd(day,4,getdate())
When datename(dw,Dateadd(day,5,getdate()))='Thursday' Then Dateadd(day,5,getdate())
When datename(dw,Dateadd(day,6,getdate()))='Thursday' Then Dateadd(day,6,getdate())
When datename(dw,Dateadd(day,0,getdate()))='Thursday' Then Dateadd(day,0,getdate())
END as duedate_Weekdue;
You can reduce that to one line of code that uses a little math, and some SQL Engine trivia.
The answers that depend on DATEPART return non-deterministic results, depending on the setting for DATEFIRST, which tells the SQL Engine what day of the week to treat as the first day of the week.
There's a way to do what you want without the risk of getting the wrong result based on a change to the DATEFIRST setting.
Inside SQL Server, day number 0 is January 1, 1900, which happens to have been a Monday. We've all used this little trick to strip the time off of GETDATE() by calculating the number of days since day 0 then adding that number to day 0 to get today's date at midnight:
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()),0)
Similarly, day number 3 was January 4, 1900. That's relevant because that day was a Thursday. Applying a little math to the number of days, and relying on the DATEDIFF function to drop fractions, which it does, this calculation will always return the next Thursday for you:
SELECT DATEADD(DAY, (DATEDIFF(DAY, 3, GETDATE())/7)*7 + 7,3);
Credit to this answer for the assist.
So your final query comes down to this:
Select
getdate() as duedate,
datepart(yy,getdate()) as duedate_yr,
datepart(ww,getdate()) as duedate_ww,
DATEADD(DAY, (DATEDIFF(DAY, 3, GETDATE())/7)*7 + 7,3) as duedate_Weekdue;
If the first day of the week is Sunday, by using the modulo operator %:
cast(dateadd(day, (13 - datepart(dw, getdate())) % 7, getdate()) as date) as duedate_Weekdue
I also applied the casting of the result to date.
Try identifying number of day in week with DATEPART and then adding enough days to go to next thursday:
declare #dt date = '2019-03-22'
declare #weekDay int
SELECT #weekDay = DATEPART(dw, #dt)
if #weekDay <= 5
select DATEADD(day, 5 - #weekDay ,#dt)
else
select DATEADD(day, 12 - #weekDay ,#dt)

Get only data from the last month (in January)

I have been using Month(Getdate())-1 for the past few months and it was working great. Now in January it is not working. Is there a way to fix this?
Assuming you are using SQL Server, you get last month by doing:
dateadd(month, -1, getdate())
Assuming you have a date column, you would get last months data by doing something like:
where month(datecol) = month( dateadd(month, -1, getdate()) ) and
year(datecol) = year( dateadd(month, -1, getdate()) )
If month and year are in separate columns, then you can modify appropriately.
Note: There are many other ways to do this calculation. This is just showing a reasonable way given the information in the question.

Capture the first of the current month to current day date range in where clause

I am selecting fields like client id, name, and service date. I am trying to write in my where clause, that every day I run my query it will capture a date range of the first of the current month to the current day.
One method would be to compare the month and the year:
where year(col) = year(getdate()) and
month(col) = month(getdate()) and
day(col) <= day(getdate()) -- this is optional, if there is no future data
Another method would be to compare to the beginning of the month. I would approach this as:
where col >= cast(dateadd(day, 1 - day(getdate), getdate()) as date)
(This assumes there is no future data in the table.)
or, better yet:
where col >= datefromparts(year(getdate()), month(getdate()), 1)
Select *
From YourTable
where SomeDateField bewteen cast(DateAdd(DD,-Day(GetDate())+1,GetDate()) as Date) and cast(getDate() as Date)
and ...
Edit: I used the BETWEEN to trap possible future date/scheduled events