SQL:一2多行,多行合并为一列

问题描述 投票:0回答:1

我有四个表,分别是tblProject(一个记录),tblTeamMembers(许多记录),tblProjectStatus(查找表)和tblProjectScoresComments(许多记录)。使用MSSQL 2017。

下面是表定义:1)tblProject:

[ProjectID] [INT] IDENTITY(1,1) NOT NULL,
[ProjectName] [NVARCHAR](150) NOT NULL,
[CommunityProblem] [NTEXT] NOT NULL,
[IctSolveCommunityProblem] [NTEXT] NOT NULL,
[TeamMemberRoles] [NTEXT] NOT NULL,
[ProjectImpact] [NTEXT] NOT NULL,
[HelpRaiseFunds] [NTEXT] NOT NULL,
[ProjectStatus] [INT] NOT NULL,
[CaptureDate] [DATE] NOT NULL

2)tblTeamMembers:

[MemberID] [INT] IDENTITY(1,1) NOT NULL,
[Person] [NVARCHAR](150) NOT NULL,
[SalRef] [NVARCHAR](50) NOT NULL,
[Email] [NVARCHAR](150) NOT NULL,
[UserName] [NVARCHAR](150) NOT NULL,
[TeamLeader] [INT] NOT NULL,
[ProjectLeader] [INT] NOT NULL,
[ProjectLeaderContactNo] [NVARCHAR](150) NULL,
[ProjectID] [INT] NOT NULL

3)tblProjectScoresComments

[RecID] [INT] IDENTITY(1,1) NOT NULL,
[ProjectID] [INT] NOT NULL,
[Score] [FLOAT] NOT NULL,
[Comments] [NVARCHAR](MAX) NULL,
[UserID] [NVARCHAR](150) NOT NULL,
[DateCaptured] [DATETIME] NOT NULL

4)tblProjectStatus

[ProjectStatusID] [INT] IDENTITY(1,1) NOT NULL,
[ProjectStatus] [NVARCHAR](100) NOT NULL

我希望结果返回所有三个表的列,但是第三个表(tblProjectScoresComments)有很多记录,对于[Score]列,应该返回平均值,并且[Comments]列应将所有注释返回为1列,每个注释应用竖线(|)分隔

我想使用类似于以下的查询:

SELECT p.ProjectID, p.ProjectName AS Project, ps.ProjectStatus, tm.Person AS ProjectLeader, 
p.CaptureDate, [AVERAGE_SCORE_FOR_ALL] AS Score, [ALL_COMMENTS_MERGED_TO_ONE_COLUMN] AS Comments
FROM dbo.tblProject AS p 
     INNER JOIN dbo.tblProjectStatus AS ps ON p.ProjectStatus = ps.ProjectStatusID 
     INNER JOIN dbo.tblTeamMembers AS tm ON p.ProjectID = tm.ProjectID 
     INNER JOIN dbo.tblProjectScoresComments AS psc ON p.ProjectID = psc.ProjectID
WHERE (tm.ProjectLeader = 1)

结果应类似于以下内容:

ProjectID   | Project                                                                                                   |   ProjectStatus    | ProjectLeader |  CaptureDate | Score   |Comments
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
1                   | Access to ICT-Makatane High School and Community Project  | Not yet decided  |Mary Ndlovu    |    2019-10-04  | 1.67      |Comment 1,Comment 2,Comment 3
2                   | Access to ICT-Makatane High School and Community Project  | Rejected         |Joe Soap       |    2019-10-04  | 3       |Comment 1,Comment 2,Comment 3

非常感谢您的帮助!

我有四个表,分别是tblProject(一个记录),tblTeamMembers(许多记录),tblProjectStatus(查找表)和tblProjectScoresComments(许多记录)。使用MSSQL2017。下表为...

sql sql-server one-to-many
1个回答
0
投票

这听起来像聚合:

© www.soinside.com 2019 - 2024. All rights reserved.