SQL datediff - People older than - sql

I have an SQL table called member in which I have member information and in that information, their birth date.
I need to get a list of all the people that are more than 25 years old. For now, I got this :
SELECT * FROM members
WHERE DATEDIFF(year, birthday, GETDATE() ) > 25
The only thing is that it doesn't take into consideration all the people that turned 25 this year so far...
How do I add to this everyone that turned 25 in January and February of this year as well ?
Would someone be able to help me out ?
Thanks !

Don't use datediff(). Just subtract the years from the current date:
where birthday < dateadd(year, -25, getdate())

Try adding 25 years to their birthday and then comparing to now. If <=, then they are older than 25.
SELECT *
FROM members
WHERE DATEADD(year, 25, birthday) <= getdate()

Related

Upper limit of the Year condition in my query is ignored

This is quite an embarrassing question but it's wasted 2 hours of my time, so I am giving up.
In below query, the second condition (which sets the upper limit of my query) is ignored by SQL Server. It returns ALL years greater than 2018, instead of returning rows from 2018 to 2021 (assuming today's year is 2020).
Please note that I would like to KEEP the years, and control this using YEARS, and not provide datetime. what am I doing wrong? why is my query returning all rows greater than 2018 (upper limit is ignored)???
--THIS QUERY SHOULD RETURN ALL ROWS WITH "STARTDATETIME"
-- WITH YEARS GREATER THAN 2018 (SO BASICALLY 2018-01-01)
-- BUT NOT THE ROWS WITH YEARS GREATER THAN ONE YEAR AHEAD OF TODAY'S DATE
-->STARTDATETIME IS DATETIME
--I'D LIKE TO MANAGE THIS QUERY BY USING YEARS (BECAUSE IT IS A PARAM IN SSRS)
SELECT STARTDATETIME FROM ACTION
WHERE (YEAR(STARTDATETIME)>='2018' --Greater than equal to 2018
AND
(YEAR(STARTDATETIME)<=(DATEADD(year, 1, GETDATE()))) --this condition is mysteriously ignored
-- I kept adding brackets.
) --but up to only one year ahead
ORDER BY STARTDATETIME DESC
What did I try? Everything imaginable (except giving actual datetime). I kept adding brackets to solve the issue, but it didn't help
YEAR() returns an integer.
DATEADD() returns a date.
These are not comparable.
Perhaps you intend:
STARTDATETIME <= DATEADD(year, 1, GETDATE())
If you want through the end of next year, I would recommend:
STARTDATETIME < datefromparts(year(getdate()) + 2, 1, 1)
That is, before the first day of 2022. This works for both dates and date/times. And, it allows indexes to be used, if available.
You are comparing int to date-time :
YEAR(STARTDATETIME) = DATEADD(year, 1, GETDATE())
You either need to call year() with dateadd() or remove year() from STARTDATETIME :
WHERE YEAR(STARTDATETIME) >= 2018 AND
YEAR(STARTDATETIME) <= YEAR(DATEADD(year, 1, GETDATE()))
On your second condition, you're comparing an year to an entire date:
(YEAR(STARTDATETIME)<=(DATEADD(year, 1, GETDATE())))
Why don't you try the following instead?
STARTDATETIME<=DATEADD(year, 1, GETDATE())

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

DB2 SQL - How to check if an employee reached age 70 years and 6 months in current year?

I want to fetch an employee who reaches age 70 years and 6 months in year. That is, he should reached 70 years and 6 months between 01/01 and 12/31 of current year. Please help.
My table has the employees date of birth, datatype DATE. Database system DB2.
We know the employee will reach 70 years 6 months in this year when:
The year of birth is 70 years before the current year and month of birth is no later than June
OR the year of birth is 71 years before the current year and the month of birth is no earlier than July.
Therefore we must filter as such:
SELECT Name FROM Employees
WHERE DateOfBirth BETWEEN '7/1/' + CAST((YEAR(GETDATE())-71) AS varchar) AND '7/1/' + CAST((YEAR(GETDATE())-70) AS varchar)
Try step by step.
If person becomes 70.5 years old on 2013-01-01, then his birthday is 1942-07-01.
If person becomes 70.5 years old on 2013-12-31, then his birthday is 1943-06-30.
Calculate these values in your programming language.
Then
SELECT * FROM empleyees WHERE birstday >= '1942-07-01' AND birstday <= '1943-06-30';
What RDBMS are you using. The answer needs date functions, and each RDBMS uses its own proprietary date functions.
In SQL Server, you could
Select case When birthdate Between
DateAdd(month, -6, Dateadd(year, -70, dateadd(dd, 1 +
datediff(dd, 0, getdate())-datepart(dy,getdate()), 0)))
And DateAdd(month, 6, Dateadd(year, -70, dateadd(dd,
datediff(dd, 0, getdate())-datepart(dy,getdate()), 0)))
(A.BRTH_DT BETWEEN (SUBSTR (CHAR(DATE(&CURRDATE) - 71 YEARS),1,4)||'-07-01') AND (SUBSTR (CHAR(DATE(&CURRDATE) - 70 YEARS),1,4)||'-06-30')
This SQL worked to fetch the Age 70.5 employees. &CURRDATE refers to Current Date.

Retrieve SQL Records Based on Past Date?

I have some database records, and one of the columns contains the date the record was added (called COMP_DATE).
I need to make a query, that will run each day, which selects records whose COMP_DATE is exactly n years, 11 months, and 15 days ago (within a 24 hour window). (I.E. 15 days before n years ago).
What would be the best way of doing this? Should I just subtract (n*356 - 15 days)? How would I accomplish this?
Thanks.
the best way will be to do it the other way around to obtain n years 11 months and 15 days ago
Remove n+1 years and add 15 days, you'll have the less room for errors
DECLARE #n as INT=<your value here>;
SELECT *
FROM records
WHERE comp_date BETWEEN Dateadd(DAY, 15, Dateadd(YEAR, -#n-1, Getdate()))
AND Dateadd(DAY, 16, Dateadd(YEAR, -#n-1, Getdate()));
Hope that helped ;)
There are functions to do date arythmetic. For example, Dateadd
(Assuming this is Microsoft SQL Server based on the question's tags.)
select * from records where
comp_date = dateadd(year,-n,dateadd(month,-11,dateadd(days, -15, GetDate())));
*assumimg comp_date is of type Date.
if comp_date is datetime column type, you'll want to search on a range (a 24 hour range). Also, if you are looking for 15 days before n years ago, the query should look like this:
select * from records where
comp_date >= dateadd(year,-n,dateadd(day, -15, getdate()))
and comp_date < dateadd(year,-n,dateadd(day, -14, getdate()));
If indeed you are wanting n years 11 months and 15 days ago, use WOPRs answer.

SQL Server 2005, Calculating upcoming birthdays from date of birth

This one has bugged me for a while now. Recently when revisiting some code I wrote for a customer a few years ago I was wondering if there is a more elegant solution to the problem.
The customer stores all of their clients information including date of birth (date time field)
They run an extract every Monday that retrieves any customer whose birthday will fall within the following week.
I.e. if the extract was run on Monday Jan 1st, Customers whose birthday fell between (and including) Monday Jan 8th -> Sunday Jan 14th would be retrieved.
My solution was to use the Datepart(dy) function and calculate all upcoming birthdays based off the customers date of birth converted to day of year, adding some logic to include for the extract being run at the end of a year.
The problem was that using Day of year throws results off by 1 day if the customer was born on a leap year and / or the extract is run on a leap-year after the 29th of Feb, so once again I had to add more logic so the procedure returned the expected results.
This seemed quite over-kill for what should be a simple task
For simplicity let’s say the table 'customer' contains 4 fields, first name, last name, dob, and address.
Any suggestions on how to simplify this would really be appreciated
Wes
Would something like this work for you?
select * from Customers c
where dateadd(year, 1900-year(dob), dob)
between dateadd(year, 1900-year(getdate()), getdate())
and dateadd(year, 1900-year(getdate()), getdate())+7
Why not use DATEPART(wk) on this year's birthday?
SET DATEFIRST 1 -- Set first day of week to monday
SELECT * FROM customer
WHERE DATEPART(wk, DATEADD(yy, DATEPART(yy, GETDATE()) - DATEPART(yy, customer.dob), customer.dob)) = DATEPART(wk, GETDATE()) + 1
It selects all customers who's birthday's weeknumber is one greater than the current weeknumber.
I think DATEADD should do the proper thing.
YEAR(GETDATE() - dbo.Patients.Dob) - 1900
I can safely assume you will never have customers born before 1900
Please Try This one.
SELECT TOP 10 BirthDate, FirstName
FROM Customers
WHERE DATEPART(mm,BirthDate) >= DATEPART(mm,GETDATE())
AND DATEPART(day,BirthDate) >= DATEPART(day,getdate())
OR DATEPART(mm,BirthDate) > DATEPART(mm,getdate())
ORDER BY DatePart(mm,BirthDate),DatePart(day,BirthDate)
this query will get upcoming birthdays including today itself