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

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

Related

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

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.

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.

SQL Date Diff disregarding Year

i want to make a select, where the users birthday(date field) is less than 30 days.
what is the best way to to do it? i tried datediff, but i don't know how to put the year aside.
Thanks
You could just use DATEPART function with dayofyear datepart value.
EDIT: honestly, there is a boundary issue in my previous answer (many thanks to Damien): e.g. 2010-12-25 and 2011-01-07 => the difference should be less then 30 days, but DATEPART(dayofyear, #date) - DATEPART(dayofyear, [Birthday]) < 30 condition would skip this record. So I added an additional contition to my answer:
DATEPART(dy, #d) - DATEPART(dy, [Birthday]) < 30 OR
(
DATEPART(mm, #d) = 12 AND
DATEPART(dy, DATEADD(m, 1, #d)) - DATEPART(dy, DATEADD(m, 1, [Birthday])) < 30
)
it adds one month to the each date in the case when the month part of the first date is December and compares the difference.
A common way is to compose a formatted date, as text, and replace the year with the current year; and parse back into a date. Apply datediff on that.
If you find out datediff returns something negative thus the birthday of this year is in the past, add 1 year, and try again. This is for the time period around New Year.
SELECT *
FROM dbo.CheckBirthDay
WHERE (CASE WHEN YEAR(BirthDay) <= YEAR(CURRENT_TIMESTAMP) THEN DATEDIFF(DD,BirthDay,CURRENT_TIMESTAMP) END < 30 )

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

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