age from dob in sql - sql

In the sql query, I am getting problem in the where clause.
I have a dob and ssn of people in a table. I need to find the youngest snr. customer. The age of youngest senior customer starts from 55. The data of DOB contains all the dob's of children,parent, senior customers. In the line "where" I have to write a condition that checks if the age is > 55 and has to be smaller amongst the senior customers.Please suggest me some ways .I posted a similar question before, but did nt get any reply that can help me in solving it.
I dont have the age parameter in my table.
SSn DOB
22 1950-2-2
21 1987-3-3
54 1954-4-7
I need to find the ssn corresponding to the age whcih has to be greater than 55 and smaller among above values .

In the script below, the sub-select finds the DOB of the youngest person 55 years of age or over; this is then used to find the corresponding SSN record(s). [This uses SQL Server syntax.]
SELECT yt.*
FROM *yourtable* yt
INNER JOIN
(
SELECT MAX(DOB) AS DOB
FROM *yourtable*
WHERE DATEADD(year, 55, DOB) < getdate()
) maxdob
ON maxdob.DOB = yt.DOB
n.b. you may find more than a single record if there is more than 1 person with the same DOB.
If you want to force this single restriction, add a TOP 1 clause in your SELECT statement.
hth

If you have the DOB then you can easily calculate the age based on the current date:
WHERE DATE_ADD(DOB, INTERVAL 55 YEAR) < NOW()
This will add 55 years to the DOB and if it is greater than the current time, it's true. This would indicate they are at least 55 years of age.

Related

SQL Query to get the Average age from multiple 'date' values

I'm needing to get a SQL Query which returns the average age of multiple data inputs in my table
Households
User
Dates
1
2002-01-01
2
2004-06-10
I want to grab both User 1 and 2 date of births and return the average age of them.
Managed to get the age from the date of births using
SELECT *, DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), Date)), '%Y') + 0 AS age
FROM Households;
I just can't get the rest of it working to then average the ages out.
Assuming that you are running MySQL, as the syntax of your SQL code suggests.
For starts, I would recommend simplifying the age computation. MySQL provides timestampdiff(), which we can use like so:
select user_id, user_date,
timestampdiff(year, user_date, current_date) age
from houshold
user_id
user_date
age
1
2002-01-01
20
2
2004-06-10
18
3
2004-11-10
17
To compute the average age over all rows of the table, we can use aggregate function avg():
select avg(timestampdiff(year, user_date, current_date)) avg_age
from houshold
avg_age
18.3333
Here is a small demo based on your sample data. Note that I renamed the columns so they do not clash with meaningful SQL names.

Cannot use having because it is not contained in an aggregate function, but cant solve because column is missing

I am trying to complete this question, but I am receiving a "Column 'DOG.DOB' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause." error, but I am stuck because there is no age column and I am confused on how I'm supposed to go about solving it. Below is the question to the problem and below the question is the desired output
Using a subquery, create a query that will show those dogs that are older than the average age of all dogs. In your output include the name of the dog and the age. Since the database does not store the age of a dog, you will need to calculate it. There are numerous functions that can help you to find the difference between two dates. To get the current system date use the getdate() function. Sort your output by the age of the dog showing the older dogs first. Rename your columns: Dog Name and Age. This query will product 359 rows. The first 10 rows will look like the following:
Dog Name Age
--------------- -----------
Rosina 10
Floris 10
Harlin 10
Martina 10
Roselin 10
Rem 10
Alie 10
Roxane 10
Nester 10
Clair 10
My Query:
select Name AS 'Dog Name',
DATEDIFF(year, getdate(), DOB) AS 'Age'
from DOG
having DATEDIFF(year, getdate(), DOB) > avg(DATEDIFF(year, getdate(), DOB))
order by AGE desc
the average calculation needs to be in it's own select statement - which will form the subquery mentioned in the question e.g.
having DATEDIFF(year, getdate(), DOB) > (subquery returning the average age of all dogs)

Using decode with to_date

If anyone could help me with the following, I'd be grateful:
I'm trying to write a code (create an alert in PowerSchool) that will indicate if a student is younger or older than average for their current grade level. (For example, as student born before 6/30/2002 is older than average for 9th grade) I can't seem to make DECODE work in conjunction with >= TO_DATE. Here's my statement:
select lastfirst, decode (dob >= to_date ('2002-06-30', 'yyyy-mm-dd'), 'old') DOB
from students
where grade_level = 9
order by lastfirst
You probably could get away with using a PowerSchool decode in your sql, but I find code easier to write when fewer languages/systems are included, so I would leave it out. I would also let SQL do the average age calculation so you don't have to supply or calculate average dates yourself (see Averaging dates in oracle sql for an explanation of the TO_DATE line).
SELECT
LastFirst AS "Student Name"
,CASE WHEN dob >= (
SELECT
TO_DATE(ROUND(AVG(TO_NUMBER(TO_CHAR(dob, 'J')))),'J')
FROM Students
WHERE Grade_Level = 9
AND Enroll_Status = 0
) THEN 'Younger' ELSE 'Older' END AS "Older or Younger?"
FROM Students
WHERE Grade_Level = 9
ORDER BY LastFirst
The subquery calculates the average birthday, and the CASE statement compares each of your records against that, reporting if it's older or younger.
In the subquery that calculates the average, I've taken the liberty of assuming you only want to compare against currently enrolled students, since withdrawn students retain the same grade level. You don't really want those students who left 10 years ago and are still listed as a 9th grader to mess with your average numbers.

select from database

For a University course I've been given the following task
Suppose that we have an employee table like (first_name, last_name, salary, hire_date, ...). There is regulation which states that every employee each year after he/she is hired, must renew his contract with company. Show how many months remain before the next renewal for each employee.
This is my attempt:
select (abs(months_between(sysdate,hire_date)/12 -
round((months_between(sysdate,e.hire_date))/12)))
from employees e
is it correct?or what will be correct implementation
You are part of the way there, but this isn't it - what you have so far will show the modulus of months since hire date divided by 12, as a fraction.
What you need is to subtract the the modulus of months since hire date divided by 12, as a whole number, from 12.
So to take an example, an employee who was hired 13 months ago will return 0.0833333 in your supplied query - you want to see a result of (12 - (the remainder of 13/12 as a whole number - ie. 1)) = 11 months to go.
Most flavours of SQL have a modulus function, although the name and syntax may vary between SQLs.
Also, I would amend your query to include e.* as well as your calculation in your select statement.
If you start with a table like this:
create table my_table (
first_name varchar(15),
last_name varchar(15),
salary integer,
hire_date date
);
insert into my_table values ('A', 'Beemer', 30000, '2011-01-15');
insert into my_table values ('B', 'Catalog', 31000, '2011-01-27');
insert into my_table values ('C', 'Doir', 45000, '2011-03-11');
you can use a SELECT statement to return a result like this one.
first_name last_name salary hire_date renewal_date days_to_renewal
--
A Beemer 30000 2011-01-15 2012-01-15 57
B Catalog 31000 2011-01-27 2012-01-27 69
C Doir 45000 2011-03-11 2012-03-11 113
You should keep in mind that "month" is a fuzzy word that most database people hate with a white-hot, burning passion. It can mean 28, 29, 30, or 31 days on a real calendar. And you will always get blamed when expectations don't match common sense.
Running your query against my data returns these values. Clearly wrong.
LAST_NAME MONTHS_TO_RENEWAL
Beemer .154442577658303464755077658303464755078
Catalog .186700642174432497013142174432497013143
Doir .310356556152927120669056152927120669056
Oracle has a months_between() function that's documented to return "the number of months between two dates". You need to know exactly what "number of months" means to this function. (Again, given that a calendar month might have 28, 29, 30 or 31 days in it.) I'd be really surprised if you're expected to do the arithmetic any other way.
I'd suggest you start with this, and fill in the three missing pieces.
select first_name, last_name, salary, hire_date,
('date arithmetic to calculate the renewal date') renewal_date,
months_between('one date', 'another date') months_to_renewal
from my_table;

query based on sql

I'm writing a query in SQL in which i have to find the youngest senior person from a data given to me.
SSn DOB
22 1950-2-2
21 1987-3-3
54 1954-4-7
The data is in the manner. And I need to find the age first so that I can write the condition of senior customers which is age >50. Since I dont have age parameter, please suggest me some ways to do it.
select * from people where year(now())-year(dob)>50 order by dob limit 1;