2

我有项目和成员表,主要目标是一对多关系。

我有很多项目和很多成员,现在我必须找到在特定项目中分配了多少成员(除了这些我没有在这里提到的表之外,我还有很多表,但你可以在我的存储过程中看到)

CREATE PROCEDURE [dbo].[SP_PROJECT_EMPLOYSSSS]
(
  @Employee_ID INT
)
AS
BEGIN
    SELECT E.Employee_ID, S.Project_Title, COUNT(E.First_Name) 
    FROM tbl_NEW_Employee AS E  
    INNER JOIN  tbl_NEW_Employee_Project AS K ON K.Employee_ID = E.Employee_ID 
    INNER JOIN dbo.tbl_NEW_Project AS S ON K.Project_ID = S.Project_ID 
    WHERE E.Is_Active=1 AND E.Employee_ID = @Employee_ID 
    Group BY E.First_Name
END

我是编程和存储过程的新手。

我收到此错误:

列 'tbl_NEW_Employee.Employee_ID' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

请帮助我使用GROUP BY子句编写此存储过程

4

2 回答 2

2

当您group by在 sql 查询中使用子句时,只有那些列可以放在select列列表中的group by列列表中。

在您的上述查询中,您在列列表中只有 First_name group by,但您正试图进入E.Employee_ID,S.Project_Titleselect列表

如果您希望选择列中的所有上述字段,那么也将它们添加到您的 group by 子句中。

SELECT E.Employee_ID,S.Project_Title,COUNT(E.First_Name) 
    FROM tbl_NEW_Employee AS E  
    INNER JOIN  tbl_NEW_Employee_Project AS K ON K.Employee_ID=E.Employee_ID 
    INNER JOIN dbo.tbl_NEW_Project AS S ON K.Project_ID=S.Project_ID 
    WHERE E.Is_Active=1 AND E.Employee_ID=@Employee_ID 
    Group BY E.Employee_ID,S.Project_Title

否则从您的选择列表中删除它们

SELECT COUNT(E.First_Name) ,E.First_Name
        FROM tbl_NEW_Employee AS E  
        INNER JOIN  tbl_NEW_Employee_Project AS K ON K.Employee_ID=E.Employee_ID 
        INNER JOIN dbo.tbl_NEW_Project AS S ON K.Project_ID=S.Project_ID 
        WHERE E.Is_Active=1 AND E.Employee_ID=@Employee_ID 
        Group BY E.Employee_ID,S.Project_Title
于 2013-07-29T12:32:49.097 回答
0

似乎是SQL Server和不是MySQL

您必须GROUP BY在要聚合的列上(即每个值仅输出一行):

SELECT E.Employee_ID,S.Project_Title,COUNT(E.First_Name) 
FROM tbl_NEW_Employee AS E  
INNER JOIN  tbl_NEW_Employee_Project AS K ON K.Employee_ID=E.Employee_ID 
INNER JOIN dbo.tbl_NEW_Project AS S ON K.Project_ID=S.Project_ID 
WHERE E.Is_Active=1 AND E.Employee_ID=@Employee_ID 
Group BY E.Employee_ID,S.Project_Title
于 2013-07-29T12:32:10.833 回答