Filter date to be greater than 24 months rather than 2 years? - sql

This is what I have so far:
SELECT ListKey
FROM Closing_List
WHERE DATEPART(YEAR,closedate) > DATEPART(YEAR,GETDATE())-2)
But I want 24 Months back.
Thanks!

SELECT ListKey
FROM Closing_List
WHERE closedate > DATEADD(MONTH, -24, GETDATE())

SELECT ListKey
FROM Closing_List
WHERE closedate > DATEADD(MONTH,-24,GETDATE())

Using DATEADD is fine as long as you know what it's doing with the dates.
GetDate() returns the current date and time. Right now for me that's 08/30/2013 02:18:14pm
Passing that through DATEADD(MONTH,-24,GETDATE()) yields 08/30/2011 02:18:14pm'
So if I were running your query with that information it would be giving me all results with a closedate greater than (not equal to) 08/30/2011 02:18:14pm. There are a couple of things to consider about that.
For one, if you have records that closed on 08/30/2011 at 1:00pm then they won't be included in your results. Moreover if your close dates don't have times at all then you won't get any records from 08/30/2011.
Also note that if you run that query on 9/2/2013 then it won't include records from 9/1/2011. That may or may not be a problem, depending on your needs.
Another solution might be:
SELECT ListKey
FROM Closing_List
WHERE closedate >= dateadd(month,datediff(month,0,getdate())-24,0)
If you run the above anytime in September of 2013 it will include all records with a close date from September 2011 to September 2013. It doesn't care about what day of the month it currently is or if the close date includes time data.

Related

SQL - Count month difference in non-consecutive date period

I am trying to extract how many months of membership a member gets up to date. As the picture shows, this member got four years of subscription since 2018. However, she stopped the subscription for a year ending in 2019. And then, restart the membership in 2020 again.
Each membership lasts for 12 months. if we look at the last membership starting from 2022-05-08, it will end up on 2023-05-08. However, I only want to get the total month count up to date(getdate - 2022-09-14).
Please advise how I could approach this matter. Thanks!
enter image description here
Assuming you were planning to apply sum(monthcount), you could wrap the monthcount within a CASE statement to checks if the vip_end is greater than today's date:
sum(case when vip_end > getdate() then ... else monthcount end)
What you do within that ... depends on whether you wanted to just count the different number of months within the date range (e.g. 31st Jan -> 01st Feb is counted as a whole month because it just considers Jan -> Feb):
datediff(month, datecreated, getdate())
or perhaps calculate the number of months based on the average days in a month:
datediff(day, datecreated, getdate())*12.0/365.25
or maybe something else... it really depends on what level of detail you want to achieve.

SQL how to get information from The Start of some # of years ago

I have looked through a few posts but either there is too much information or I just don't quite understand what I am looking for.
eg: How to get the first and last date of the current year?
In a table I have sales orders for the last 20 years, all I want is to show the orders from January 1st of three years before until whatever the current date is.
AND ShipDate >= (YEAR(ShipDate)-3)
Which doesn't work.
AND ShipDate >= DATEADD(YEAR,-2,GETDATE())
Which Shows exactly 2 years ago from whatever the current day is.
I want to be able to eventually create reports that show each year in the last three on their own but this is the first step and I am not doing well so far!
I want is to show the orders from January 1st of three years before until whatever the current date is.
The best method in SQL Server is:
where shipdate >= datefromparts(year(getdate()) - 3, 1, 1)
For any date in 2021, this returns all rows from 2021, 2020, 2019, and 2018. If you don't want 2018, then use - 2 rather than - 3.
This formulation has the option of being optimizer friendly (allowing the use of indexes and partitions, for example). Two other common says to write this are not optimizer friendly:
where datediff(year, shipdate, getdate()) <= 3
where year(shipdate) >= year(getdate()) - 3
(Once again, the "3" might be "2" depending on what you really intend.)
you were close:
AND YEAR(ShipDate) >= (YEAR(ShipDate)-3)
You were comparing a year to a date

Report that updates yearly

I have created a report that is supposed to look at the number of baptisms at our church for the ministry year. The Ministry year runs from Aug 1 - July 31. I currently have the report set to tell me the names of anyone that has a baptism date greater than 8/1/2016. But I would need to change that year each year for it to report properly. so I wanted to use a Case statement to have it update each year, but i am getting an error message with this: (The error is in the where clause, so I didn't include the entire report)
WHERE (P.organization_id = 1) AND
((CandidateProcesses_BaptismDate68.datetime_value) between (
case
When datepart(month, getdate()) < 8 then ('8/1/'+ datepart(year, getdate()))
When datepart(month, getdate()) >7 then ('8/1/'+
datepart((year,getdate())-1))End) and Getdate())
Does anyone see why I am getting an error?
Thanks!
You are getting an error trying to add a string and a number. You could fix that using datename() rather than datepart(). But, I think this is a simpler approach:
WHERE (P.organization_id = 1) AND
year(dateadd(month, -7, CandidateProcesses_BaptismDate68.datetime_value)) = year(dateadd(month, -7, getdate()))
This subtract 7 months to get the "ministry year" and then compares that to the current date minus seven months. That is, it subtracts 7 months and then normalizes on the calendar year.
This is a bit more expensive than your version, because it cannot use an index on CandidateProcesses_BaptismDate68(datetime_value). However, I doubt the database of baptisms is so large that the query will take very long anyway. (If that is an issue, then your version can be made to work with some simple modifications.)

Get the month and year now then count the number of rows that are older then 12 months in SQL/Classic ASP

I know this one is pretty easy but I've always had a nightmare when it comes to comparing dates in SQL please can someone help me out with this, thanks.
I need to get the month and year of now then compare it to a date stored in a DB.
Time Format in the DB:
2015-08-17 11:10:14.000
I need to compare the month and year with now and if its > 12 months old I will increment a count. I just need the number of rows where this argument is true.
I assume you have a datetime field.
You can use the DATEDIFF function, which takes the kind of "crossed boundaries", the start date and the end date.
Your boundary is the month because you are only interested in year and month, not days, so you can use the month macro.
Your start time is the value stored in the table's row.
Your end time is now. You can get system time selecting SYSDATETIME function.
So, assuming your table is called mtable and the datetime object is stored in its date field, you simply have to query:
SELECT COUNT(*) FROM mtable where DATEDIFF(month, mtable.date, (SELECT SYSDATETIME())) > 12

SQL Query to Count Number of Days, Excluding Holidays/Weekends

I have a "workDate" field and a "receivedDate" field in table "tblExceptions." I need to count the number of days beteen the two. workDate always comes first - so, in effect, it's kind of like workDate is "begin date" and receivedDate is "end date". Some exclusions make it tricky to me though:
First, I need to exclude holidays. i do have a table called "tblHolidays", with one field - holidayDate. I have holidays stored up through next year, so maybe I can incorporate that into the query?
Also, most flummoxing is that work dates can never occur on weekends, but received dates can. So, i somehow need to exclude weekends when i'm counting, but allow for a weekend if the received date happens to fall on a saturday or sunday. so, if the work date is June 3rd, 2011, and received date is June 11th, 2011, the count of valid days would be 7, not 9.
Any help on this is much appreciated. Thanks!
Something like this should give you the number of days with the holidays subtracted:
select
days = datediff(day, workDate, receivedDate)
- (select count(*) from tblHolidays where holidayDate >= workDate and holidayDate < receivedDate)
from
tblExceptions
Note that the date functions differ between database systems. This is based on MS SQL Server, so it may need adapting if you are using some other database.
If you have a table full of dates to include (non-weekends, non-holidays, etc.) and you knew when the 'begin' date and the 'end' date is, then you can do something roughly like this:
select count(*) from tblIncludedDates where beginDateValue <= dateField and endDateValue >= dateField
to get the number of valid days between those dates.