SQL平均年龄比较函数返回null

时间:2015-06-14 21:37:49

标签: mysql sql function datetime

所以,我在MySQL工作,编写一个函数来平均表中女性和男性的年龄并对它们进行比较,然后返回更高的函数。日期格式为YYYY-MM-DD,我正在使用DATEDIFF()。该函数似乎工作正常,但是当我运行脚本时,我得到的只是一个带有空值的消息框,而不是它应该输出的响应。

USE tennis;

DROP PROCEDURE IF EXISTS AverAge;

DELIMITER //

CREATE PROCEDURE AverAge()
BEGIN
    DECLARE averWomen DECIMAL(3,2);
    DECLARE averMen DECIMAL(3,2);

    SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE()))
    INTO averWomen
    FROM PLAYERS
    WHERE sex = 'F';

    SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE()))  
    INTO averWomen
    FROM PLAYERS
    WHERE sex = 'M';

    IF averWomen > averMen THEN
        SELECT CONCAT('The average age of women is higher. It is ', averWomen) AS message;
    ELSEIF averMen > averWomen THEN
        SELECT CONCAT('The average age of women is higher. It is ', averMen) AS message;
    ELSE
        SELECT CONCAT('The average age of men and women is equal. It is ', averWomen, ' for women and ', averMen, ' for men.') AS message;
    END IF;
END//

DELIMITER ;

CALL AverAge();

有人可以找到我弄乱的地方吗?

修改

USE tennis;

DROP PROCEDURE IF EXISTS AverAge;

DELIMITER //

CREATE PROCEDURE AverAge()
BEGIN
    DECLARE averWomen DECIMAL(10,6);
    DECLARE averMen DECIMAL(10,6);

    SELECT AVG(EXTRACT(year FROM CURDATE()) - EXTRACT(YEAR FROM BIRTH_DATE))
    INTO averWomen
    FROM PLAYERS
    WHERE SEX = 'F';

    SELECT AVG(EXTRACT(year FROM CURDATE()) - EXTRACT(year FROM BIRTH_DATE))
    INTO averMen
    FROM PLAYERS
    WHERE SEX = 'M';

    IF averWomen > averMen THEN
        SELECT CONCAT('The average age of women is higher. It is ', averWomen) AS message;
    ELSEIF averMen > averWomen THEN
        SELECT CONCAT('The average age of women is higher. It is ', averMen) AS message;
    ELSE
        SELECT CONCAT('The average age of men and women is equal. It is ', averWomen, ' for women and ', averMen, ' for men.') AS message;
    END IF;
END//

DELIMITER ;

CALL AverAge();

所以,这就是我所做的工作。

2 个答案:

答案 0 :(得分:0)

当你声明变量averMen时,你还没有初始化它。应该计算averMen的查询正在计算averWomen。

尝试更改......

SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE()))  
INTO averWomen
FROM PLAYERS
WHERE sex = 'M';

进入

SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE()))  
INTO averMen
FROM PLAYERS
WHERE sex = 'M';

答案 1 :(得分:0)

您的查询方式太复杂了。为什么不使用条件聚合?

SELECT (CASE WHEN avg_f > avg_m
             THEN CONCAT('The average age of women is higher. It is ', avf_f) 
             WHEN avg_m > avg_f
             THEN CONCAT('The average age of men is higher. It is ', avg_m) 
             ELSE CONCAT('The average age of men and women is equal. It is ', avg_f, ' for both.')
        END) AS message
FROM (SELECT AVG(CASE WHEN sex = 'M' THEN DATEDIFF(BIRTH_DATE, CURDATE()) END) as avg_m,
             AVG(CASE WHEN sex = 'F' THEN DATEDIFF(BIRTH_DATE, CURDATE()) END) as avg_f
      FROM PLAYERS
     ) a

为什么在只使用一个查询时会使用五个查询?