2

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.

1
  • just add c.Name to the GROUP BY clause Commented Sep 20, 2013 at 19:45

2 Answers 2

2

You need to add Cows.name to the group by list:

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

If you are using group by every field you select needs to either be in the list being grouped by or have an aggregate function applied to the column (AVG, MIN, MAX, SUM, etc) as there can be multiple values returned for each of the non-grouped-by columns.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed I do. Thank you sir.
1

Change

GROUP BY p.CowID

to

GROUP BY c.Name

This won't work if you have multiple cows with the same name - in that case their total MilkQuantity will be combined into a single record.

5 Comments

What if two different cows have the same name?
OP doesn't return ID in the query, so I guess he doesn't care about this scenario. If we do group by both ID and Name and return just name - you would just see duplicate names - which is not much information
In your scenario two separate Bessie's could combine and be a supercow even if they weren't. Relevant even if he is not selecting the id.
I liked typing supercow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.