我正在尝试创建一个函数,该函数将返回每天平均产生超过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的了解相当有限,我希望有人帮我解决这个问题。
答案 0 :(得分: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
,则您选择的每个字段都需要位于要分组的列表中,或者将集合函数应用于列(AVG
,MIN
,{{ 1}},MAX
等)因为每个非分组列都可以返回多个值。
答案 1 :(得分:1)
更改
GROUP BY p.CowID
到
GROUP BY c.Name
如果您有多个具有相同名称的奶牛,这将无效 - 在这种情况下,他们的总MilkQuantity将合并为一个记录。