我正在尝试创建一个函数,该函数将返回平均每天生产超过 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 的了解相当有限,我希望有人能帮助我解决这个问题。