2

我正在尝试创建一个函数,该函数将返回平均每天生产超过 20 升牛奶的所有奶牛的表格。这是我想出的代码:

CREATE FUNCTION SuperCows (@year int)
RETURNS @supercows TABLE (
    Name nvarchar(50),
    AvgMilk decimal(4,2)
)
BEGIN
    INSERT @supercows
        SELECT c.Name, AVG(CAST(p.MilkQuantity AS decimal(4,2))) FROM MilkProduction AS p
        INNER JOIN Cows AS c ON c.IDCow = p.CowID
        WHERE YEAR(p.Date) = @year
        GROUP BY p.CowID
        HAVING AVG(CAST(p.MilkQuantity AS decimal(4,2))) > 20
    RETURN
END
GO

我在尝试创建函数时遇到的错误是:

Column 'Cows.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我对 SQL 的了解相当有限,我希望有人能帮助我解决这个问题。

4

2 回答 2

2

您需要按列表将 Cows.name 添加到组中:

SELECT c.Name, AVG(CAST(p.MilkQuantity AS decimal(4,2))) FROM MilkProduction AS p
    INNER JOIN Cows AS c ON c.IDCow = p.CowID
    WHERE YEAR(p.Date) = @year
    GROUP BY p.CowID, c.Name
    HAVING AVG(CAST(p.MilkQuantity AS decimal(4,2))) > 20

如果您正在使用group by您选择的每个字段,则需要在分组依据的列表中或将聚合函数应用于列(AVGMINMAXSUM等),因为每个非分组依据可以返回多个值列。

于 2013-09-20T19:44:28.827 回答
1

改变

GROUP BY p.CowID

GROUP BY c.Name

如果您有多头同名的奶牛,这将不起作用 - 在这种情况下,它们的总 MilkQuantity 将合并为一条记录。

于 2013-09-20T19:45:30.697 回答