我有三个与此 SQL 语句相关的表。
项目
- 项目记录 ID
- 项目名称
项目_竞赛类别
- ProjectCompetitionCategoryRecordId
- 项目记录 ID
- CompetitionCategoryRecordId
比赛类别
- CompetitionCategoryRecordId
- 比赛类别名称
我试图从我的表中检索的是ProjectRecordId, ProjectName, CompetitionCategoryName
值。
但是 aProject
可能会参与多个Competition Category
. 我需要将信息放在一行中,并将比赛放在它自己的列中。
下面的例子
1. 1 | Project No 1 | Competition 1, Competition 2
2. 2 | Project No 2 | Competition 2, Competition 3, Competition 4
3. 3 | Project No 3 | Competition 1, Competition 4
这是我拥有的当前 SQL 语句:
DECLARE @Data VARCHAR(2000)
DECLARE @pID INT
DECLARE @pName VARCHAR(300)
SELECT
@pID = Project.ProjectRecordId,
@pName = Project.ProjectName,@Data = COALESCE(@Data + ',' + CompetitionCategoryName, CompetitionCategoryName)
FROM
Project_CompetitionCategory
INNER JOIN
CompetitionCategory ON Project_CompetitionCategory.CompetitionCategoryRecordId = CompetitionCategory.CompetitionCategoryRecordId
INNER JOIN
Project ON Project_CompetitionCategory.ProjectRecordId = Project.ProjectRecordId
WHERE
Project.ProjectRecordId = 10
SELECT
@pID AS 'Project Record ID',
@pName AS 'Project Name',
@Data AS Competition,
(SELECT COUNT(ProjectRecordId) FROM Presentation WHERE ProjectRecordId = @pID) AS 'Number of Recorded Presentations'
如果我删除
WHERE Project.ProjectRecordId = 10
然后它只获取最后一个值,CompetitionCategory
然后搞砸了。
像下面的东西。
1. 15 | Project No 15 | Competition1, Competition 2, Competition 3, Competition 2, Competition 4
我已经阅读了这篇stackoverflow文章的各种答案Concatenate many rows into a single text string?
并用谷歌搜索在网站上找到解决方案,例如
- http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html
- http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
但是我仍然找不到解决方案。我正在使用 SQL Server 2008 R2。我是 SQL 新手,想了解为什么无法获得我想要的数据。
提前致谢。