是否可以在存储函数中返回 SUM 的最大值? MYSQL

问题描述 投票:0回答:1

我正在处理一个动物保护区的数据库,人们可以在那里向特定动物捐款。我正在尝试创建一个函数来返回捐赠者捐赠最多的动物。我正在处理的表称为捐款,列是donation_id、donor_id、animal_id、amount 和date_donated。

我已经尝试过这个查询(及其更改),但不断出现错误。我希望函数返回 favAnimal 作为所选捐赠者捐赠最多的动物的 Animal_id。

DELIMITER //
CREATE FUNCTION FindFavAnimal(p_donor_id INT(3))
RETURNS INT(3)
BEGIN
DECLARE favAnimal INT(3)
SELECT SUM(amount) AS sum_amount
FROM donations
WHERE donor_id = p_donor_id
GROUP BY animal_id;
SET favAnimal = MAX(sum_amount);
RETURN favAnimal;
END //
DELIMITER ;

非常感谢任何帮助!

sql mysql phpmyadmin stored-functions
1个回答
0
投票

你就快到了。由于您说只需要选定捐赠者捐赠最多的动物的 Animal_id,因此您不需要在外部查询中返回

SUM(amount)
。试试这个

DELIMITER //
CREATE FUNCTION FindFavAnimal(p_donor_id INT)
RETURNS INT
BEGIN
    DECLARE favAnimal INT;
    DECLARE maxAmount INT;

    -- Get the maximum sum of donations for the given donor
    SELECT MAX(sum_amount) INTO maxAmount
    FROM (
        SELECT SUM(amount) AS sum_amount
        FROM donations
        WHERE donor_id = p_donor_id
        GROUP BY animal_id
    ) AS donation_sums;

    -- Get the animal_id corresponding to the maximum sum
    SELECT animal_id INTO favAnimal
    FROM (
        SELECT animal_id, SUM(amount) AS sum_amount
        FROM donations
        WHERE donor_id = p_donor_id
        GROUP BY animal_id
    ) AS animal_donation_sums
    WHERE sum_amount = maxAmount;

    RETURN favAnimal;
END //
DELIMITER ;
© www.soinside.com 2019 - 2024. All rights reserved.