Expressing age between two years - sql

Question
How could I express the following statement in my query?
Between 4 and 5 years old
SQL Query
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) <=2
Get all Assets that are more than one year old from todays date
What I want to say?
Get all assets between 4 and 5 years old

Be very careful using datediff(year). It counts the number of year boundaries between two dates. So, the difference between 2014-12-31 and 2015-01-01 is 1.
In addition, I recommend putting the functions on the getdate() value rather than on the column. This allows an index to still be used on the column ("sargability"). So, something like this should do what you want:
where AcquiredDate >= dateadd(year, -5, GetDate()) and
AcquiredDate < dateadd(year , -3, GetDate())
On 2015-01-01, this will retrieve rows acquired between 2010-01-1 and 2011-12-31, which seems to be the intent of the question.

check for SQL's BETWEEN OPERATOR here
SQL Between
SELECT * FROM TABLE NAME WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) BETWEEN 4 and 5

Use BETWEEN http://www.w3schools.com/sql/sql_between.asp
SELECT *
FROM table
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) BETWEEN 4 and 5

Related

What is an efficent way of calculating a person's age at a particular time in the past? [duplicate]

This question already has answers here:
How to calculate age (in years) based on Date of Birth and getDate()
(40 answers)
Closed 17 days ago.
I am trying to calculate the age of a person given a particular date in the past; let's just say '02-01-2020' for this example.
I have something like this:
SELECT person.name,
CASE
WHEN DATEADD(YEAR, DATEDIFF(YEAR, person.birthdate, '02-01-2020'), person.birthdate) < '02-01-2020'
THEN DATEDIFF(YEAR, person.birthdate, '02-01-2020')-1
ELSE DATEDIFF(YEAR, person.birthdate, '02-01-2020')
END AS calculated_age,
FROM PersonTable
[...]
I don't think this works for potential birthdates that fall after '02-01-2020', and I was wondering if there is just a better way to do this?
I use this approach in my current project
DECLARE #Date DATETIME = '2020-02-01'
select DATEDIFF(YEAR,person.birthDate, #Date) -
CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, person.birthDate, #Date), person.birthDate) > #Date THEN 1 ELSE 0 END
I would get the difference between the two dates in days and then divide this number by 365.25 accounting for leap years.
SELECT person.name,
FLOOR(DATEDIFF(DAY, person.birthdate, '02-01-2020') / 365.25) AS calculated_age,
FROM PersonTable
[...]
This might cause some inaccuracies if you are using these results in other calculations due to the fractional part of the year.
Here's another way to get your desired result:
SELECT (CAST(FORMAT(CAST('02-01-2020' AS datetime2),'yyyyMMdd') AS int) - CAST(FORMAT(CAST(person.birthdate AS datetime2),'yyyyMMdd') AS int))/10000 AS calculated_age
FROM PersonTable

Get data from certain date to last 10 days in SQL

I want to get data from certain date to last 10 days. I have tried the following code but it is not working.
DECLARE #wrking_date DATE = '2022-02-08'
SELECT
a,
CAST(LogDate as date) as theDate,
b,c
FROM magic_table
Where b = '123'
AND #wrking_date >= DATEADD(DAY,10, GETDATE())
What I am doing wrong ?
EDIT
I have also tried adding AND LogDate between '2022-02-08' and DATEADD(DAY, -10, '2022-02-08') this does not work
As it's currently written, your query doesn't get filtered with your AND condition because neither GETDATE() not #wrking_date are part of the queried table. I'm assuming you want to filter based on the column LogDate. To get the values between #wrking_date and 10 days ago, you can use BETWEEN:
AND LogDate BETWEEN #wrking_date AND DATEADD(DAY, -10, GETDATE())
Notice this: To get the date from 10 days ago, you need to use -10 in the DATEADD function.
Edit
As I got from your comments, you're trying to get the data between the defined #working_date and 10 days back from there. You could achieve that by using this:
AND LogDate BETWEEN DATEADD(DAY, -10, #wrking_date) AND #wrking_date

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

SQL query to delete records from a query

I am trying to write 2 queries to delete records where dates are greater than a certain date:
The first one:
delete from RPT_HistSnapEng_temp
where ForecastDate> DATEADD(WEEK,7,CAST(GETDATE() AS DATE))
This query deletes records when forecastdate is greater than 7 weeks from today
The second one is:
delete from RPT_HistSnapEng_temp
where ForecastDate< DATEADD(WEEK,-6,CAST(GETDATE() AS DATE))
This query deletes records when forecastdate is less than 6 weeks from today.
So basically, this should filter out records from Dec 2015 - Nov 2016 and only show records from previous 6 weeks and next 7 weeks from today.
Even though the query runs, its not deleting records. I cannot hardcode dates because I will be using this query on a rolling basis inside a SSIS package.
Your current where clauses are trying to grab records that are both less than a date in the past AND greater than a date in the future. I think you (and the other answer) should be using or.
But, since this looks like a temp table that you are loading to then report with, I would adjust your insert to simply grab the records you are looking for, rather than loading more than you need and then deleting.
select *
from RPT_HistSnapEng -- base table name?
where cast(ForecastDate as date) between dateadd(week, -6, cast(current_timestamp as date)) and dateadd(week, 7, cast(current_timestamp as date))
Just add your insert to that if it gets the records you need.
However, to directly answer your question about deletes, you can change this query to simply use NOT between:
delete
from RPT_HistSnapEng_temp
where cast(ForecastDate as date) not between dateadd(week, -6, cast(current_timestamp as date)) and dateadd(week, 7, cast(current_timestamp as date))
As you can see, I like the use of between (which is inclusive of the date arguments) for this type of range check rather than getting caught up in using >= and < or confusing the and and or which you've seemingly done. I also like the ANSI standard current_timestamp over the t-sql specific getdate() but they are equivalent.
Try "ww" or "wk" instead of "week" in the dateadd function. Try a SELECT statement to get the records you want to delete:
SELECT ID, ForecastDate
FROM RPT_HistSnapEng_temp
WHERE CAST(ForecastDate AS DATE) > DATEADD(ww,7,CAST(GETDATE() AS DATE))
OR CAST(ForecastDate AS DATE) < DATEADD(WEEK,-6,CAST(GETDATE() AS DATE))
ORDER BY ForecastDate
To Delete just remove the SELECT and the ORDER BY:
DELETE
FROM RPT_HistSnapEng_temp
WHERE CAST(ForecastDate AS DATE) > DATEADD(ww,7,CAST(GETDATE() AS DATE))
OR CAST(ForecastDate AS DATE) < DATEADD(WEEK,-6,CAST(GETDATE() AS 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.