MySQL按年月日计算年龄

Posted

技术标签:

【中文标题】MySQL按年月日计算年龄【英文标题】:MySQL Calculate age by year month and day 【发布时间】:2014-09-03 08:47:44 【问题描述】:

我想显示患者年龄的数据。

mysql> 从 sampelaja 中选择 nama,gender,dob,TIMESTAMPDIFF(YEAR,dob,now()) 作为年龄; +-----------------+--------+------------+------+ |名 |性别 |出生日期 |年龄 | +-----------------+--------+------------+------+ |里兹基扬迪 | 1 | 2010-05-21 | 4 | |西蒂霍迪亚 | 0 | 1980-03-15 | 34 | | Aisyah Az-zahra | 0 | 1986-08-17 | 28 | |参数 | 0 | 2005-12-13 | 8 | |恩加迪明 | 1 | 2014-08-28 | 0 | +-----------------+--------+------------+------+ 10 行一组(0.00 秒)

这里有一个问题,当有一个4天大的婴儿被视为0岁时 我想要这样的结果

+-----------------+--------+------------+------+- ------+------+ |名 |性别 |出生日期 |年份 |月 |天 | +-----------------+--------+------------+------+- ------+------+ |里兹基扬迪 | 1 | 2010-05-21 | 4 | 3 | 13 | |西蒂霍迪亚 | 0 | 1980-03-15 | 34 | 5 | 18 | | Aisyah Az-zahra | 0 | 1986-08-17 | 28 | 0 | 16 | |参数 | 0 | 2005-12-13 | 8 | 8 | 20 | |恩加迪明 | 1 | 2014-08-28 | 0 | 0 | 6 | +-----------------+--------+------------+------+- ------+------+

【问题讨论】:

检查这个可能对你有帮助forums.mysql.com/read.php?10,378024,378912 您可以得到 TIMESTAMPDIFF(DAY) 然后除以 365 表示年份,余数大于 30 然后除以 30(平均月数),其余为天数。或 TIMESTAMPDIFF(YEAR) 和 MONTH AND DAY 的组合,然后按 YEAR * 12 和 DAY 按 YEAR * 365 AND MONTH * 30 的值减去月份 或查看此处了解其他一些方法。 ***.com/questions/18756546/… 如果结果是这样,我想如何显示年龄小于30天的患者的数据? 【参考方案1】:

您可以使用模数来确定月数和天数:

SELECT
      nama
    , gender
    , dob
    , TIMESTAMPDIFF( YEAR, dob, now() ) as _year
    , TIMESTAMPDIFF( MONTH, dob, now() ) % 12 as _month
    , FLOOR( TIMESTAMPDIFF( DAY, dob, now() ) % 30.4375 ) as _day
FROM 
    sampelaja

结果是:

+-----------------+--------+------------+-------+--------+------+
| nama            | gender | dob        | _year | _month | _day |
+-----------------+--------+------------+-------+--------+------+
| Rizkiyandi      |      1 | 2010-05-21 |     4 |      3 |   13 |
| Siti Khodijah   |      0 | 1980-03-15 |    34 |      5 |   19 |
| Aisyah Az-zahra |      0 | 1986-08-17 |    28 |      0 |   17 |
| Paritem         |      0 | 2005-12-13 |     8 |      8 |   20 |
| Ngadimin        |      1 | 2014-08-28 |     0 |      0 |    6 |
+-----------------+--------+------------+-------+--------+------+

从上个月的生日日期到今天的天数。

数字30.4375我使用这个公式计算:[DAYS IN YEAR]/12,其中[DAYS IN YEAR] = 365.25

【讨论】:

谢谢兄弟。这个查询是否可以用作表视图?因为如果患者超过 10 天,我想制定一个标准 可以,可以添加WHERE子句过滤10年以内的记录:WHERE TIMESTAMPDIFF( YEAR, dob, now() ) < 10。或者你可以创建CHECK CONSTRAINT 一个测试用例是dob='2018-02-15 00:00:00', now='2018-04-17 00:00:00', 你的查询返回0年2月0天,这是不正确的,你能帮我解决这个问题吗@Nicolai @MajbahHabib,你们的日期之间有 61 天。因为我使用了近似值(1 个月是 30.4375 天),所以查询返回 0.1250 天。函数FLOOR 将此值四舍五入为零。您可能更愿意将这部分的一天算作一整天。为了使这个使用函数CEIL 而不是FLOOR。希望这会有所帮助。【参考方案2】:

您应该能够使用下面的查询来计算它。该查询计算确切的年、月和日。

这个信息也可以在mysql日期计算页面找到:http://dev.mysql.com/doc/refman/5.0/en/date-calculations.html

SELECT 
    nama, 
    gender, 
    dob,

    /* Select the number of years */
    TIMESTAMPDIFF(
        YEAR,
        dob,
        CURDATE()
    ) AS years,

    /* Select the number of months by adding the number of years to the 'dob' date field */
    TIMESTAMPDIFF(
        MONTH, 
        DATE_ADD(
            dob ,
            INTERVAL TIMESTAMPDIFF(YEAR,dob,CURDATE()) YEAR
        ),
        CURDATE()
    ) AS months,

    /* Select the number of days by adding the number of years and number of months to the 'dob' field */
    TIMESTAMPDIFF(
        DAY,
        DATE_ADD(
            DATE_ADD(
                dob ,
                INTERVAL TIMESTAMPDIFF(YEAR,dob,CURDATE()
            ) YEAR),
            INTERVAL TIMESTAMPDIFF(
                MONTH, 
                DATE_ADD(
                    dob ,
                    INTERVAL TIMESTAMPDIFF(YEAR,dob,CURDATE()) YEAR
                ),
                CURDATE()
            ) MONTH
        ),
        CURDATE()
    ) AS days
FROM
    sampelaja

【讨论】:

谢谢兄弟。你回答正确。但是太长了。它是否可以用作表格视图?我想选择一个答案但不能,必须选择一个合适的答案:-(【参考方案3】:

已接受答案中的问题

接受答案中的方法很好,但闰年在生日时会搞砸。以下是一些测试用例:

create table sample (dob datetime,now datetime);
insert into sample (dob,now)values
('2012-02-29', '2013-02-28'),
('2012-02-29', '2016-02-28'),
('2012-02-29', '2016-03-31'),
('2012-01-30', '2016-02-29'),
('2012-01-30', '2016-03-01'),
('2011-12-30', '2016-02-29');

SELECT
      date_format(dob,'%Y-%m-%d')
    , date_format(now,'%Y-%m-%d')
    , TIMESTAMPDIFF( YEAR, dob, now ) as _year
    , TIMESTAMPDIFF( MONTH, dob, now ) % 12 as _month
    , FLOOR( TIMESTAMPDIFF( DAY, dob, now ) % 30.4375 ) as _day
 FROM sample

       DOB         NOW YEAR     MONTH  DAY
2012-02-29  2013-02-28    0     11      30  -- 28 days would be better
2012-02-29  2016-02-28    3     11      29  -- 28 days would be better
2012-02-29  2016-03-31    4      1       0  -- 2 days would be better
2012-01-30  2016-02-29    4      0      30  
2012-01-30  2016-03-01    4      1       0  -- 2 days should be right
2011-12-30  2016-02-29    4      1       0  -- The right answer should be 4 years 1 months 30 days

这是我的方法,只使用算术

select
       DATE_FORMAT(dob,'%Y-%m-%d'),
       DATE_FORMAT(now,'%Y-%m-%d'),
       FLOOR(( DATE_FORMAT(now,'%Y%m%d') - DATE_FORMAT(dob,'%Y%m%d'))/10000),
       FLOOR((1200 + DATE_FORMAT(now,'%m%d') - DATE_FORMAT(dob,'%m%d'))/100) %12,
      (sign(day(now) - day(dob))+1)/2 * (day(now) - day(dob)) + 
      (sign(day(dob) - day(now))+1)/2 * (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d') - INTERVAL 1 DAY)
                                         - day(dob) + day(now))
       -- Explain: if the days of now is bigger than the days of birth, then diff the two days
       --          else add the days of now and the distance from the date of birth to the end of the birth month 
from sample

测试用例和结果:

       DOB         NOW  YEARS   MONTHS  DAYS
2012-02-29  2013-02-28     0    11      28
2012-02-29  2016-02-28     3    11      28
2012-02-29  2016-03-31     4     1       2
2012-01-30  2016-02-29     4     0      30
2012-01-30  2016-03-01     4     1       2
2011-12-30  2016-02-29     4     1      30

【讨论】:

【参考方案4】:

当日期是同一天时,Jaugar Chang 的答案中的天数列会出现故障。我认为以下内容对此进行了纠正:

(SELECT CASE sign(day(now)-day(dob)) 
  WHEN 0 THEN 0 
  WHEN 1 THEN day(now)-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(now)) END)
  as days

为了完整起见,Jaugar 答案的修订版本如下:

SELECT 
FLOOR(( DATE_FORMAT(NOW(),'%Y%m%d') - DATE_FORMAT(dob,'%Y%m%d'))/10000) as year,
FLOOR((1200 + DATE_FORMAT(NOW(),'%m%d')-DATE_FORMAT(dob,'%m%d'))/100) %12 as month,
CASE sign(day(NOW())-day(dob))
  WHEN 0 THEN 0
  WHEN 1 THEN day(NOW())-day(dob)
  ELSE (DAY(STR_TO_DATE(DATE_FORMAT(dob + INTERVAL 1 MONTH,'%Y-%m-01'),'%Y-%m-%d')-INTERVAL 1 DAY)-day(dob)+day(NOW())) END as day
FROM sampelaja

【讨论】:

【参考方案5】:

这是我用来计算年龄的查询,以年、月和日为单位

SELECT nama, gender, dob
,DATE_FORMAT(CURDATE(), '%Y') - DATE_FORMAT(dob, '%Y') - (DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS years
,PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(dob, '%Y%m') ) AS months
,DATEDIFF(CURDATE(),dob) AS days
FROM sampelaja

【讨论】:

【参考方案6】:

下面的函数是从各种资源中复制过来的,合并为一个。 这将以年、月和日的形式返回完整的日期。 也可以修改它以显示任何一个。 此外,current_time 被用作输入,以便我们也可以计算相对于任何其他日期的年龄。

DROP function IF EXISTS `calculate_age`;

DELIMITER $$
CREATE FUNCTION `calculate_age`(`dob` DATE,  `current_time` DATETIME) 
RETURNS varchar(100) CHARSET utf8
BEGIN
DECLARE years varchar(10);
DECLARE months varchar(9);
DECLARE days varchar(7);
SELECT FLOOR(DATEDIFF(current_time, dob)/365) INTO years;
SELECT FLOOR((DATEDIFF(current_time,dob)/365 - FLOOR(DATEDIFF(current_time,dob)/365))* 12) INTO months;
SELECT CEILING((((DATEDIFF(CURDATE(),dob)/365 
- FLOOR(DATEDIFF(CURDATE(),dob)/365))* 12) - FLOOR((DATEDIFF(CURDATE(),dob)/365 - FLOOR(DATEDIFF(CURDATE(),dob)/365))* 12))* 30) into days;
RETURN CONCAT_WS
            ( ', '
        , CASE WHEN years = 0 THEN NULL ELSE CONCAT(years,'y') END
        , CASE WHEN months = 0 THEN NULL ELSE CONCAT(months, 'm') END
        , CASE WHEN days = 0 THEN NULL ELSE CONCAT(days, 'days') END
        );
END$$

DELIMITER ;

【讨论】:

【参考方案7】:
SELECT concat(
  cast(TIMESTAMPDIFF(YEAR, str_to_date('14/08/2018','%d/%m/%Y'), str_to_date('14/05/2019','%d/%m/%Y')) AS char),' years ',
    cast(MOD(TIMESTAMPDIFF(MONTH, str_to_date('14/08/2018','%d/%m/%Y'), str_to_date('14/05/2019','%d/%m/%Y')), 12) as char), ' months ',
  cast(DATEDIFF(str_to_date('14/05/2019','%d/%m/%Y'),
  DATE_ADD(DATE_ADD(str_to_date('14/08/2018','%d/%m/%Y'), INTERVAL
  TIMESTAMPDIFF(YEAR, str_to_date('14/08/2018','%d/%m/%Y'),str_to_date('14/05/2019','%d/%m/%Y'))
  YEAR),
  INTERVAL MOD(TIMESTAMPDIFF(MONTH, str_to_date('14/08/2018','%d/%m/%Y'),str_to_date('14/05/2019','%d/%m/%Y')),12) MONTH)) AS char),' days') as Age

【讨论】:

【参考方案8】:
SELECT TIMESTAMPDIFF(year, dt.dt, NOW()) AS y,
       TIMESTAMPDIFF(month, dt.dt, NOW())%12  AS m,
       TIMESTAMPDIFF ( day, 
        DATE_ADD( adddate(curdate(), day( dt.dt) - day(curdate())), interval 
        -(day( dt.dt)>day(curdate())) month), 
        curdate()) as days
FROM (select date('1975-08-07') as dt ) as dt;

【讨论】:

以上是关于MySQL按年月日计算年龄的主要内容,如果未能解决你的问题,请参考以下文章

EXCEL表格中有年龄,计算年月日公式是啥?

如何用excel计算年龄,要具体到年月日

出生年月日提取年龄公式是啥?

知道出生年月日,怎么用公式计算年龄?

Java 根据年月日精确计算年龄

出生年月提取年龄公式