I am trying to create a function that will return a table of all cows that produced on average more than 20 liters of milk per day. This is the code I came up with:
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
The error that I get when trying to create the function is this:
Column 'Cows.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
My knowledge of SQL is fairly limited and I was hoping someone cold help me with solving this.