Update age column by one year - sql

How to update the age column by only one year for each row in the table,
so how to get the year of that column and increase it by 1.
My data looks like:
ID name age
1 sarah 1992-05-26 00:00:00
2 suzan 1991-05-20 00:00:00

For your specific question you can add one year onto each date with a simple DateAdd:
UPDATE DataTable SET Age = DATEADD(year, 1, Age)
However, I would store the Date of Birth in the database and calculate the Age in the Business Layer or wherever it needs to be displayed.
For reference, if you do store the Date of Birth, then the age can be calculated with a simple query using a DateDiff function to calculate the number of whole years between the date of birth and todays date:
SELECT DT.Name
, DT.DateOfBirth
, DATEDIFF(year, DT.DateOfBirth, GETDATE()) As Age
FROM DataTable DT

your query should look like this:
Update yourTable set age = DATEADD(yy,1,age)
this will increase year by 1

Related

How to calculate date based on yyyy-mm-dd

I am looking for a simple query to calculate someones age based on yyyymmdd. I don't need to keep the records updated throughout time, I just need the age as of today.
Example - 19731026 is the birthdate for one record. I want to create a new column named age and calculate that birthdate to their current age which would be 48 years old.
If your database is Oracle you can use:
select floor(months_between(sysdate, to_date('19731026','YYYYMMDD'))/12) as age
from dual;
AGE
----------
48

How to get value only for the current month

I would like to know if we can got values from date if the date is in the current month
For example, If I have :
date value
28/06/2021 50
02/07/2021 100
05/07/2021 18
Then I search to have :
02/07/2021 100
05/07/2021 18
because 28/06/2021 is not in the current month
thanks in advance !
In Mysql you can use now() and month() functions to get the current date ang extract the month.
Select *
from table
where <your filters>
having MONTH(NOW()) = MONTH( table.date_field)
Different databases like oracle , postrest change the name of this functions , so you must find it
TSQL
select * from tbl
where MONTH(date)=month(getdate())
You'll want to match the YEAR along with the MONTH if you will have data that spans more than a year.
SELECT date, value
FROM table
WHERE YEAR(date) = YEAR(GETDATE()) AND MONTH(date) = MONTH(GETDATE())

checking age of a person, the person has date of birth stored as a date

select
//
from
//
where
//this is the place i need help with
I have a table person with column dob date.
I want to be able to select rows of people aged 1 or more.
some mock date:
name dob
person 1 13-DEC-2014
person 2 24-JAN-2011
person 3 05-MAY-2013
person 4 17-APR-2014
person 5 21-DEC-2013
person 6 11-NOV-2014
in this scenario i would expect the names 'person 2', 'person 3' and 'person 5' to be listed in the output. i know how to do the select and from statement in my scenario, just not a where. any help would be greatly appreciated.
select *
from person
where dob <= add_months( trunc(sysdate), -12 )
will return everyone whose birth date is more than 12 months before the current date. sysdate returns the current date and time. trunc removes the time component (setting it to midnight). Then add_months subtracts 12 months.
I would use ADD_MONTHS():
SELECT * FROM person
WHERE dob <= TRUNC(ADD_MONTHS(SYSDATE, -12));
In the above I'm actually adding -12 months (or 1 year -- equivalent to subtracting 12 months) to the value of SYSDATE.
Calculate the threshold and compare dob to that:
where dob <= add_months(sysdate, -12))
Using a constant expression for the threshold would also mean that if an index existed on dob then it would be a candidate for usage. Even if an index didn't exist, it would still be much more efficient than ccukating a date from (every value of) dob and comparing it to today.
to_char(sysdate,'YYYY') - to_char(dob,'YYYY')>1

Update table based on last date of previous month

Please would you advise how I could create a column which showed a timestamp/date for each row indicating the last day of the previous month. For example:
Name Surname DOB Timestamp
John Smith 1970/04/20 2015/02/28
Cindy Smith 1975/03/20 2015/02/28
Now this could be for 5000 people and I've just given 2 rows to show you what I mean.
CREATE table employees (Name NVARCHAR(30),Surname NVARCHAR (30),DOB DATETIME,Timestamp DATETIME)
To tackle the problem of the dates not showing hours,minutes, seconds, I am using
CONVERT(CHAR(10),Timestamp,113)
Do you use a While loop or something to create a column which shows the same timestamp for each row?
Thanks.
I think the easiest way is to just subtract the day of the month from the date:
select t.*, dateadd(day, -day(timestamp), timestamp)
from table t;
EDIT: In an `update:
update t
set timestamp = dateadd(day, -day(dob), dob)
In addition, you shouldn't use convert to remove the time component of a date, you should simply case to date. If dob had a time component (which seems unlikely):
update t
set timestamp = cast(dateadd(day, -day(dob), dob) as date)
Assuming the table have records with Timestamp column as NULL. Then with the following update query will update all records with previous month's last day.
UPDATE employees
SET [Timestamp] = CAST(DATEADD(DAY,-1,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))AS DATE)
WHERE [Timestamp] IS NULL
The inner DATEADD will find first day of current month and outer DATEADD decrements the date by one which result in previous month's last date.
When the month in GETDATE() is April, the records with NULL values will be updated with 31-Mar-2015. When the GETDATE() becomes May, the records with NULL values will be updated with 30-Apr-2015 ie, it won't update the records which have already values or which are updated.

Name Change SQL Query - Positive Attrition

Using SQL Server Management Studio and I've got an Employee table which has records for every time something changes with an employee, be it manager, pay-scale, etc. etc. etc. Whenever a change is made, and EffectiveEndDateKey will be marked for the last time that complete field was relevant and the next record will have the next day as and EffectiveBeginDateKey.
What I'm trying to do is extract the last record an employee had BEFORE they changed their job title in the last month. The goal is IF an employee changes their job title within a given month that would count as "Positive Attrition" and we're trying to figure out how much positive attrition we get in a given month. (It's always for the previous month so in the where statement I'm pulling just changes for the previous month).
Take a look below:
In this example, on July 4th, John Doe went from being an Apple Store Clerk to the next day being a manager, so there was a job title change. What I want is to pull the record in the red box (Jon's last day - in July - when her was an Apple Store Clerk before he became a manager) b/c that tells me that an EffectiveEndDateKey had a change that resulted in a job title change.
So the where statement is going to have a Cast in it to convert the EffectiveEndDateKey to a date and then look at last months data, pulling only records that have EffectiveEndDateKeys from last month (July) and what I need help with is the part where those records must ALSO have a different job title.
if say someone changed job titles on July 31st (so their new job title/EffectiveBeginDateKey was 20130801), that would still count as 1 positive attrition and we'd want to pull the last record from July 31st.
Any thoughts?
You can do this with a self-join:
select eprev.*
from Employee e
Employee eprev
on e.EmployeeId = eprev.EmployeeId and
cast(cast(e.EffectiveBeginDateKey as varchar(255)) as datetime) =
cast(cast(eprev.EffectiveEndDateKey as varchar(255)) as datetime) + 1
where cast(cast(e.EffectiveBeginDateKey as varchar(255)) as datetime) >= dateadd(mm, -1, getdate()) and
eprev.JobTitle <> e.JobTitle;
The key here is the conversion of the number to a datetime. The format YYYYMMDD is easily convertible, when it is a string. So, convert the number of a string first, then to a datetime. The rest is just the mechanics of the join.
Since your strings are effectively just dates in ISO format (yyyymmdd), you don't even have to convert it to datetime, you could just get previous row:
select E.EmployeeID, E.JobTitle, ENEXT.JobTitle as NextJobTitle
from Employee as E
outer apply (
select top 1 T.JobTitle
from Employee as T
where
T.EmployeeID = E.EmployeeID and
T.EffectiveEndDateKey > E.EffectiveEndDateKey
order by T.EffectiveEndDateKey asc
) as ENEXT
where
E.JobTitle <> ENEXT.JobTitle and
E.EffectiveEndDateKey >= convert(nvarchar(8), dateadd(mm, datediff(mm, 0, getdate()) - 1, 0), 112)
see SQL FIDDLE example