Sql查询同时加入和聚合

时间:2012-02-24 11:42:07

标签: sql sql-server

如何在给定ProjectID的ProjectCompletion表中选择ProjectPossibilityRatio列的总和?我找不到总和:

SELECT pp.ProjectID,
   pp.ProjectAlias,
   Sum(pd.projectpossibilityratio)
FROM   project pp
   INNER JOIN projectcompletion pc
     ON pp.projectId = pc.projectID
   JOIN projectprocedure pd
     ON pd.projectprocedureID = pc.projectprocedureID
GROUP  BY pd.projectpossibilityratio

以下是表格定义:

Create TABLE ProjectType(
ProjectTypeID int identity(1,1),
ProjectTypeName nvarchar(100),
Description nvarchar(200),
primary key(ProjectTypeID)
)


CREATE TABLE Project(
ProjectID int identity(1,1),
ProjectAlias nvarchar(100),
ProjectTypeID int foreign key references ProjectType(ProjectTypeID),
MandatedCompanyID int foreign key references Company(CompanyID),
Iscurrent bit,
BuySide bit,
TeamID int foreign key references WorkTeam(TeamID),
ProjectTurnOver varchar(100),
ProjectStartDate Datetime
primary key(ProjectID))



CREATE TABLE ProjectProcedure(
ProjectProcedureID int identity(1,1),
ProjectProcedureName nvarchar(100),
ProjectProcedureDescription nvarchar(200),
ProjectType int foreign key references ProjectType(ProjectTypeID),
ProjectProcedurePosition int,
ProjectProcedureTime smallint,
ProjectPossibilityRatio int,
Primary Key(ProjectProcedureID))

CREATE TABLE ProjectCompletion(
ProjectID int foreign key references Project(ProjectID),
ProjectProcedureID int foreign key references ProjectProcedure(ProjectProcedureID),
StartDate Datetime,
IsCompletedDate Datetime
Primary Key(ProjectID,ProjectProcedureID)
)

2 个答案:

答案 0 :(得分:2)

将您选择的所有列名称添加到列表组中。

答案 1 :(得分:1)

试试这个:

  SELECT pp.ProjectID,pp.ProjectAlias,Sum(pd.projectpossibilityratio)
    FROM project pp INNER JOIN projectcompletion pc ON pp.projectId=pc.projectID 
    JOIN projectprocedure pd ON pd.projectprocedureID=pc.projectprocedureID 
    GROUP BY pp.ProjectID,pp.ProjectAlias

我同意LeftyX,你应该回去接受答案