如何将重复的数据行放入单个列中

时间:2015-01-28 17:38:35

标签: sql sql-server

我有一个返回项目ID,项目名称和项目类型的查询。有些项目有多种类型,因此我会多次获得相同的项目ID,因为它们将具有多个项目类型。许多项目只有一种类型。

它正在做什么的例子:

| Project_ID |   Project_Name    | Project_Type  |
|   94850    |   Convert to C#   |    .Net       |
|   94850    |   Convert to C#   |     SQL       |

这就是我想要它做的事情:

| Project_ID |   Project_Name    | Project_Type  |
|   94850    |   Convert to C#   |  .Net, SQL    |

除了项目类型之外,我不希望以这种方式进行旋转。这会是PIVOT还是其他什么东西?

SELECT PL.Project_ID,
       PL.Project_Name,
       PT.Project_Type
FROM   Project_List PL
INNER JOIN Project_Types PT ON PL.Project_ID = PT.Project_ID
WHERE  ProjectDate BETWEEN (@Start) AND (@End)

1 个答案:

答案 0 :(得分:3)

您可以使用STUFF()函数(https://msdn.microsoft.com/en-us/library/ms188043.aspx)。

CREATE TABLE #temp (
    Project_ID int,
    Project_Name nvarchar(255),
    Project_Type nvarchar(255)
);
GO
INSERT INTO #temp 
SELECT 94850, 'Convert to C#', '.Net' UNION ALL
SELECT 94850, 'Convert to C#', 'SQL' UNION ALL
SELECT 94851, 'Convert to Java', 'Java'
GO

SELECT 
    Project_ID,
    Project_Name,
        STUFF((SELECT ',' + Project_Type FROM #temp tt Where tt.Project_ID = t.Project_Id
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM #temp t
GROUP BY Project_ID, Project_Name;

DROP table #temp;

结果:

Project_ID  Project_Name    Project_Types
94850   Convert to C#   .Net,SQL
94851   Convert to Java Java