query based on sql - 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;

Related

group by sql oracle

I have a table with multiple fields, among which are: num1 (INTEGER), name(STRING) and datatime(TIMESTAMP). I would like to get the sample with name, sum(num1) and count(num1) grouped by month. I'm trying to do this:
SELECT name, sum(num1), count(num1) from mytable group by to_char(datatime, 'YYYY-MM')
But it doesn't work. Help me, please, and sorry for my English:)
Sum not sun
Group By not grouped by
all non-aggregates from select must be in the group by so add name.
.
SELECT name, sum(num1), count(num1)
FROM mytable
GROUP BY to_char(datatime, 'YYYY-MM'), name
Generally if you're going to group your data by yyyy-mm you would generally want to see that in the select... but maybe you have your reasons... otherwise how do you tell multiple values of name apart? What's in ()'s are not in your results so... which John is which?
John 123 23 (1990-01)
John 234 44 (1990-02)
John 323 22 (1990-03)

SQL Query on find individuals that age is over 60 as of a specific date

Im new to stack so please go easy on me. Ive looked all over the web and cant find anything that really helps me.
So I need to provide details of all regular academics working in the Computing Department who were
over 60 years old as of 31/12/2014.
my trouble comes with how would I approach showing data of someone 60+ could you minus one date from another date? or is there is possible sql command that I am missing.
my attempt:
SELECT *
FROM staff, department
WHERE DOB <= '31/12/1964'
AND staff.department_ID = department.department _ID
There are functions to calculate the difference between dates, but the most efficient is to first calculate the date that a person would be born to be 60 at 2014-12-31. That way you make a direct comparison to a value, so the database can make use of an index if there is one.
Example for Oracle:
select
PersonId, FirstName, LastName
from
Person
where
Born <= add_months(date '2014-12-31', -60 * 12)
Example for MySQL (eventhough you removed the MySQL tag):
select
PersonId, FirstName, LastName
from
Person
where
Born <= date_sub('2014-12-31' 60 year)
I think In SQL SERVER
Select Datediff(DAYS,'05-19-2015','05-21-2015')
In My SQL
SELECT TIMESTAMPDIFF(HOUR, start_time, end_time)
as difference FROM timeattendance WHERE timeattendance_id = '1484'
The oracle add_months function will help you.
where yourfield < add_months(date '1964-12-31', 60*12 )

I need to find the minimum and average age of students from the birth day

I have a table 'Students' which contains the 'DateOfBirth' of students. I need an SQL statement that I can use in a query to give me the average and minimum ages as fields with those names?I don't want to have to add an age field I just want a SQL statement I can copy and paste that will return me what I need.
SELECT MIN(DateOfBirth) AS Min Age, AVG(DateOfBirth) AS Avg Age FROM Students;
At the moment all the suggestions I have found ask me to specify a value when I run and I have no idea why?
You should first calculate age from date of birth then find average of age
Select AVG(Datediff("yyyy",DateOfBirth,getdate())) as AVGage from Students
Select MIN(Datediff("yyyy",DateOfBirth,getdate())) as MINage from Students
you can also calucate avg,min in one query
Select AVG(Datediff("yyyy",DateOfBirth,getdate())) as AVGage ,
MIN(Datediff("yyyy",DateOfBirth,getdate())) as MINage
from Students
FOR MS ACCESS DB:
Now() provides date and time
Date() provides the date
Time() provides the time
You can Use Date() Function
Select AVG(Datediff("yyyy",DateOfBirth,DATE())) as AVGage ,
MIN(Datediff("yyyy",DateOfBirth,DATE())) as MINage
from Students
Here is SQLFIDDLE FOR SQLSERVER:
SELECT *
FROM Students
GROUP BY DateOfBirth
ORDER BY DateOfBirth DESC
SELECT MIN(DateOfBirth) AS MinAges
FROM Students
SELECT AVG(DateOfBirth) AS AverageAges
FROM Students
Use aggregate functions AVG and MIN.. you can easily google it btw ...To count the age you can use getDate function and count the age - depends on your format of column DateOfBirth ..
select AVG((getDate()-DateOfBirth)/365) as avgAge ,
MIN ((getDate()-DateOfBirth)/365) as minAge
from Students

age from dob in 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.

Advice on database design / SQL for retrieving data with chronological order

I am creating a database that will help keep track of which employees have been on a certain training course. I would like to get some guidance on the best way to design the database.
Specifically, each employee must attend the training course each year and my database needs to keep a history of all the dates on which they have attend the course in the past.
The end user will use the software as a planning tool to help them book future course dates for employees. When they select a given employee they will see:
(a) Last attendance date
(b) Projected future attendance date(i.e. last attendance date + 1 calendar year)
In terms of my database, any given employee may have multiple past course attendance dates:
EmpName AttandanceDate
Joe Bloggs 1st Jan 2007
Joe Bloggs 4th Jan 2008
Joe Bloggs 3rd Jan 2009
Joe Bloggs 8th Jan 2010
My question is what is the best way to set up the database to make it easy to retrieve the most recent course attendance date? In the example above, the most recent would be 8th Jan 2010.
Is there a good way to use SQL to sort by date and pick the MAX date?
My other idea was to add a column called ‘MostRecent’ and just set this to TRUE.
EmpName AttandanceDate MostRecent
Joe Bloggs 1st Jan 2007 False
Joe Bloggs 4th Jan 2008 False
Joe Bloggs 3rd Jan 2009 False
Joe Bloggs 8th Jan 2010 True
I wondered if this would simplify the SQL i.e.
SELECT Joe Bloggs WHERE MostRecent = ‘TRUE’
Also, when the user updates a given employee’s attendance record (i.e. with latest attendance date) I could use SQL to:
Search for the employee and set the
MostRecent value to FALSE
Add a new record with MostRecent set to TRUE?
Would anybody recommended either method over the other? Or do you have a completely different way of solving this problem?
To get the last attendance date use the group function called MAX, i.e.
SELECT MAX(AttandanceDate)
FROM course_data
WHERE employee_name = 'Joe Bloggs'
To get the max attendance date for all the employees:
SELECT employee_name, MAX(AttandanceDate)
FROM course_data
GROUP BY employee_name
ORDER BY employee_name
Query above will NOT return data for employees who haven't attended any courses. So you need to execute a different query.
SELECT A.employee_name, B.AttandanceDate
FROM employee AS A
LEFT JOIN (
SELECT employee_id, MAX(AttandanceDate) AS AttandanceDate
FROM course_data
GROUP BY employee_id
) AS B ON A.id = B.employee_id
ORDER BY A.employee_name
For employees who haven't attended any course, the query will return a NULL AttendanceDate.
The flag is redundant. The other way how to get last attend day by employee:
select top 1 AttandanceDate
from course_data
WHERE employee_name = 'Joe Bloggs'
order by AttandanceDate desc
This may already be the case, but the output from the AttandanceDate columns makes me suspicious that that column may not be a datetime column. Most RDBMS's have some sort of date, time, and/or date time data types to use for storing this information. In which KandadaBoggu's AND OMG Ponies responses are perfect. But if you are storing your dates as strings you WILL have issues trying to do any of their suggestions.
Using a date time data type usually also opens you to the possibilites of obtaining date details like:
e.g. SELECT YEAR(2008-01-01) will return 2008 as an integer.
If you are running SQL Server 2005 or 2008 or later, you can use row_number() do something like the following. This will list everyone, with their most recent attendance.
with temp1 as
(select *
, (row_number() over (partition by EmpName order by AttandanceDate descending))
as [CourseAttendanceOrder]
from AttendanceHistory)
select *
from temp
where CourseAttendanceOrder = 1
order by EmpName
This could be put into a view so you can use it as needed.
However, if you always will be focused on one individual at a time, it may be more efficient to make a stored procedure that can use statements like select max(AttandanceDate) for just the person you are working on.