在SQL Server 2008中连接动态列?

时间:2013-07-19 20:59:00

标签: sql sql-server-2008 concatenation

说我有下表:

MemberName | ProjectCode | HoursWorked
John Smith | ABC, Inc.   |     5     
John Smith | Intel, Inc. |     3     
Mike Jones | Sesame St.  |     10    

这是我以前的陈述:

SELECT MemberName, ProjectCode, SUM(HoursWorked)
FROM table
GROUP BY MemberName, ProjectCode
ORDER BY MemberName

如果添加了一个额外的列,将特定成员的所有项目代码和小时数连接到一列,我将如何产生以下结果?

MemberName | HoursWorked | Details
John Smith |      8      | ABC, Inc.-5, Intel, Inc.-3
Mike Jones |      10     | Sesame St.-10

1 个答案:

答案 0 :(得分:1)

您可以使用FOR XML PATH将多行数据连接成一行:

;with cte as
(
  select membername, hoursworked,
    projectcode +'-'+cast(hoursworked as varchar(10)) projectcode
  from yourtable
)
select c.membername,
  sum(c.hoursworked) hoursworked,
  STUFF(
         (SELECT ', ' + projectcode
          FROM cte c2
          where c.membername = c2.membername
          FOR XML PATH (''))
          , 1, 1, '')  AS details
from cte c
group by c.membername;

请参阅SQL Fiddle with Demo