所以这里是上下文:开发一个ASP.NET MVC 4 Web应用程序,我在我的数据库中有一个表 ProductAllocations ,它由2个外键组成:一个来自我的表产品和表人中的另一个。我有另一张表车辆,其中包含表格的外键产品
我想选择按产品分组的分配及其信息(产品可以多次分配)。这是我的存储过程:
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
但是,Group By子句生成错误: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.
我正在使用Visual Studio 2010。
我是SQL的新手,所以我不知道发生了什么。
答案 0 :(得分:3)
您分组的字段 ,您需要使用聚合sum
,max
等,或者您需要包含列该条款,请参阅以下链接:SQL Group By& summarizing values
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
,p.FirstName
,p.LastName
,pa.EndDate
,pr.PurchaseDate
,pr.SerialNumber
,pr.CatalogPrice
,v.PlateNumber
,v.FirstCirculationDate
,v.FirstDrivingTax
,v.UsualDrivingTax;
答案 1 :(得分:1)
使用Group BY
时,您应该在Group By
子句中放置要选择的字段,还是应该对它们使用聚合函数,例如
SELECT
pa.Id_Product,Min(p.FirstName) as Firstname,Min(p.LastName) as LastName
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
你应该知道你想要使用什么聚合函数,有很多Min,max,Sum ......
有关详细信息,请阅读此GROUP BY (Transact-SQL)
答案 2 :(得分:1)
要使用GROUP BY函数,您需要确保SELECT语句中的所有字段都在聚合函数中(例如SUM()或COUNT()),或者它们需要在GROUP BY函数中。
答案 3 :(得分:0)
您不必将聚合函数与Group By一起使用,但是任何未受聚合函数但仍被选中的列都需要包含在Group By中
您究竟想要对此查询做什么?