I am trying to calculate the age based on the birthDate in MySQL using SQL statement.
My birthDate was varchar() and in this format: 29/11/1994 (DD/MM/YYYY).
My SQL statement:
SELECT DATEDIFF(YY, birthDate, GetDate()) AS Age
FROM bookedevent be INNER JOIN account a
ON be.bookedEventBY = a.accountName WHERE a.accountID = 1
However, when I test in MySQL workbench, I am getting this error message: Incorrect parameter count in the call DATEDIFF.
ANy guides?
Thanks in advance.
You are using SQL Server syntax in MySQL. That won't work. You can use TIMESTAMPDIFF():
SELECT TIMESTAMPDIFF(YEAR, birthDate, CURDATE()) AS Age
FROM bookedevent be INNER JOIN
account a
ON be.bookedEventBY = a.accountName
WHERE a.accountID = 1;
Note that the semantics for TIMESTAMPDIFF() are different than for DATEDIFF() in SQL Server. However, TIMESTAMPDIFF() is probably closer to what you really want.
Use this code
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birthDate, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birthDate, '00-%m-%d')) AS age
FROM bookedevent be INNER JOIN
account a
ON be.bookedEventBY = a.accountName
WHERE a.accountID = 1;
Related
I want to get details of the user between two ages from date of birth. My conditions are,
Calculate the age from DOB
Find the user details between two ages
My tables is,
id username phone dob
-------------------------------------
1 Jithin 123456 31/12/1990
2 Binoy 235612 12/12/1991
3 Jibin 353453 12/12/1996
I have create mysql query as below
SELECT username, DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS age FROM tbl_user WHERE age BETWEEN 20 AND 30
But the above code shows an error the column age not found. How to fix this problem. Any alternate way to find age from dob and compare it.
It does not work because you can't use an alias right away. Use a subquery around it or repeat the calculation. There is a shorter way to calculate it:
SELECT TIMESTAMPDIFF(YEAR, dob, CURDATE()) AS age
from tbl_user
where TIMESTAMPDIFF(YEAR, dob, CURDATE()) between 20 and 30
You could use subquery:
SELECT *
FROM (SELECT username,
DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y') -
(DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS age
FROM tbl_user) sub
WHERE sub.age BETWEEN 20 AND 30;
Column age from SELECT clause is not visible in WHERE at the same level. You could either wrap it with subquery or repeat entire expression.
I have the below query:
SELECT Date(time) AS date, COUNT(*) AS total FROM branches INNER JOIN
stats ON branches.branch_id = stats.branch_id WHERE stats.time BETWEEN
'$from' AND '$to' AND branches.bgroup='$group' GROUP BY date;
But when I run this query on SQL Server I get the error:
error SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL
Server]'Date' is not a recognized built-in function name.
How do I convert to SQL Server?
SQL Server has no date() function. Use cast() instead:
SELECT CAST(time as DATE) AS dte, COUNT(*) AS total
FROM branches INNER JOIN
stats
ON branches.branch_id = stats.branch_id
WHERE stats.time BETWEEN '$from' AND '$to' AND
branches.bgroup = '$group'
GROUP BY CAST(time as DATE)
ORDER BY CAST(time as DATE);
I have this query in Rails (mysql database).
planSubscriptions = PlanSubscription.find_by_sql(["SELECT ps.*
FROM plan_subscriptions ps, plans p, states s
WHERE p.name = 'Unlimitted'
AND s.name = 'Confirmed'
AND p.id = ps.plan_id
AND s.id = ps.state_id
AND date_format(ps.updated_at + INTERVAL 1 MONTH,'%Y-%m-%d') <= date_format(NOW(),'%Y-%m-%d')"])
It´s not working because malformed format string - %Y
I need to compare only the date (not the times). What is the right syntax?
MySQL is perfectly capable of comparing date values directly:
... (DATE(ps.updated_at + INTERVAL 1 MONTH) < curdate())
I am trying to query a huge database (aprroximately 20 millions records) to get some data. This is the query I am working on right now.
SELECT a.user_id, b.last_name, b.first_name, c.birth_date FROM users a
INNER JOIN users_signup b ON a.user_id a = b.user_id
INNER JOIN users_personal c ON a.user_id a = c.user_id
INNER JOIN
(
SELECT distinct d.a.user_id FROM users_signup d
WHERE d.join_date >= '2013-01-01' and d.join_date < '2014-01-01'
)
AS t ON a.user_id = t.user_id
I have some problems trying to retrieve additional data from the database. I would like to add 2 additional field to the results table:
I am able to get the birth date but I would like to get the age of the members in the results table. The data is stored as 'yyyy-mm-dd' in the users_personal table.
I would like to get the total days since a member joined till the day the left (if any) from a table called user_signup using data from join_date & left_date (format: yyyy-mm-dd).
Or you can do just this ...
SELECT
TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age_in_years,
TIMESTAMPDIFF(MONTH, birthday, CURDATE()) AS age_in_month,
TIMESTAMPDIFF(DAY, birthday, CURDATE()) AS age_in_days,
TIMESTAMPDIFF(MINUTE, birthday, NOW()) AS age_in_minutes,
TIMESTAMPDIFF(SECOND, birthday, NOW()) AS age_in_seconds
FROM
table_name
Try this:
SELECT a.user_id, b.last_name, b.first_name, c.birth_date,
FLOOR(DATEDIFF(CURRENT_DATE(), c.birth_date) / 365) age,
DATEDIFF(b.left_date, b.join_date) workDays
FROM users a
INNER JOIN users_signup b ON a.user_id a = b.user_id
INNER JOIN users_personal c ON a.user_id a = c.user_id
WHERE b.join_date >= '2013-01-01' AND b.join_date < '2014-01-01'
GROUP BY a.user_id
You can use datediff function to find number of days between two days like
select datediff(date1,date2) from table
select datediff(curdate(),date2) from table
Getting the current age in years:
SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 AS age FROM table_name;
How this works:
datediff(date1, date2) gives the difference between two dates in days. Note that the date format of 'birthday' here is date: YYYY-MM-DD.
from_days converts days into a date format
date_format function extracts with '%Y' only the four digit year. Don't use '%y', because you only get a two digit year and some people are older then 99 years.
multiply the string with 1. This is a 'hack'. MySQL will convert a string like 'YYYY' into an integer.
Getting the current age in month (unlikley, but someone may need this)
SELECT (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 * 12)
+ (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%m') * 1) AS age_in_months
FROM table_name;
How this works:
Mostly the same as age in years above.
The years get muliplied by 12. A (earth) year has 12 months.
In the next step the months are extracted the same way as the years, but instead the flag '%Y' must be changed to '%m'.
At the end the two values are added together.
Getting the current age in days is as simple as this:
SELECT DATEDIFF(DATE(NOW()), birthday) AS age_in_days FROM table_name;
Alternative code:
SELECT
DATE_FORMAT(age_date, '%Y') * 1 AS age_in_years,
(DATE_FORMAT(age_date, '%Y') * 1 * 12) + (DATE_FORMAT(age_date, '%m') * 1) AS age_in_months,
age_in_days
FROM
(SELECT
FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)) AS age_date,
DATEDIFF(DATE(NOW()), birthday) AS age_in_days
FROM table_name) AS age_date;
What I am trying to do is have a field called 'age' autopopulate from a persons date of birth when a row is added - the trick is the persons date of birth resides in anouther field.
My two tables are:
student
student_id (PK), first_name, last_name, date_of_birth
fitness_report
report_id (PK), test_date, test_period, age_tested, student_id (FK)
ideally the age_tested will be caluclated from the test_period however happy to use ()NOW as that'll be within reasonable limits.
Obviously what i need to do here is create a trigger - but not sure on the SELECT statement to get the age to populate. Help is much appreciated.
As rwilliams said, it is not advisable to store the age_tested as it is redundant but if it is what you want to do you can wrap a simple trigger around Mosty's solution -
CREATE TRIGGER fitness_report_insert BEFORE INSERT ON `fitness_report`
FOR EACH ROW
BEGIN
SET NEW.age_tested = (SELECT DATE_FORMAT(NEW.test_period, '%Y') - DATE_FORMAT(student.date_of_birth, '%Y') - (DATE_FORMAT(NEW.test_period, '00-%m-%d') < DATE_FORMAT(student.date_of_birth, '00-%m-%d')) FROM student WHERE student.student_id = NEW.student_id);
END
This assumes that test_period is a date as previously mentioned by Mosty. I have not tried this as I do not have access to a server right now so it may need a little tweaking.
UPDATE: You could try the following as a starting point for your stats -
SELECT
DATE_FORMAT(test_period, '%Y') - DATE_FORMAT(date_of_birth, '%Y') - (DATE_FORMAT(test_period, '00-%m-%d') < DATE_FORMAT(date_of_birth, '00-%m-%d')) AS age,
s.gender,
AVG(r.score) AS score
FROM student s
INNER JOIN fitness_report r
ON s.student_id = r.student_id
GROUP BY age, s.gender
This is how to get current age:
select s.name, s.date_of_birth,
date_format(now(), '%Y') - date_format(date_of_birth, '%Y') -
(date_format(now(), '00-%m-%d') < date_format(date_of_birth, '00-%m-%d'))
as age
from s
Example
This is how to get age up to the test_period (shouldn't it be test_date?):
select s.name, s.date_of_birth, r.test_period,
date_format(test_period, '%Y') - date_format(date_of_birth, '%Y') -
(date_format(test_period, '00-%m-%d') < date_format(date_of_birth, '00-%m-%d'))
as age
from r
join s on s.id_student = r.student_id
Example