Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By clause causing error

So here is the context : Developping an ASP.NET MVC 4 web app, I have in my database a table ProductAllocations which is composed of 2 foreign keys : one from my table Products and the other from the table Persons. I have another table, Vehicles which contains a foreign key of the table Products

I want to select the allocations and their information grouped by a product (a product can be allocated several time). Here is my stored procedure :

ALTER PROCEDURE GetAllVehicles

AS

BEGIN

    SET NOCOUNT ON 

    SELECT 

    p.FirstName,
    p.LastName,
    pa.EndDate,
    pr.PurchaseDate,
    pr.SerialNumber,
    pr.CatalogPrice,
    v.PlateNumber,
    v.FirstCirculationDate,
    V.FirstDrivingTax,
    v.UsualDrivingTax

    FROM bm_ProductAllocations AS pa

    INNER JOIN bm_Persons AS p ON pa.Id_Person = p.Id_Person
    INNER JOIN bm_Products AS pr ON pa.Id_Product = pr.Id_Product
    INNER JOIN bm_Vehicles AS v ON pr.Id_Product = v.Id_Product

    GROUP BY pa.Id_Product

END

However, the Group By clause is generating an error : Column 'bm_Persons.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. I'm working with Visual Studio 2010.

I'm new to SQL so I have no idea about what's going on.

like image 920
Traffy Avatar asked Dec 04 '25 00:12

Traffy


1 Answers

To use a GROUP BY function you need to make sure all of the fields in your SELECT statement are in aggregate functions (e.g. SUM() or COUNT()), or they need to be in the GROUP BY function.

like image 133
XN16 Avatar answered Dec 06 '25 16:12

XN16



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!