用于在单元格中显示多个记录的SQL Server查询

时间:2016-12-19 10:15:52

标签: sql-server sql-server-2012

我有两张桌子:

员工 -

EmployeeID      Title       EmployeeFirstName       EmployeeLastName
1001            Mr          Peter                   Parker  
1002            Ms          Nancy                   Hall

HoursWorked -

EmployeeID      HoursWorked
1001            15
1001            30
1001            45
1002            15
1002            30
1002            40

我写了以下查询:

Select Distinct 
E.EmployeeID EmployeeID,
E.Title Title,
E.FirstName EmployeeFirstName,
E.LastName EmployeeLastName,
HW.HoursWorked HoursWorked,
From Employee E
Inner Join HoursWorked HW ON E.EmployeeId = HW.EmployeeId

给出了以下输出:

EmployeeID      Title       EmployeeFirstName       EmployeeLastName        HoursWorked
1001            Mr          Peter                   Parker                  15
1001            Mr          Peter                   Parker                  30
1001            Mr          Peter                   Parker                  45
1002            Ms          Nancy                   Hall                    15
1002            Ms          Nancy                   Hall                    30
1002            Ms          Nancy                   Hall                    40

我想以下列格式显示记录:

EmployeeID      Title       EmployeeFirstName       EmployeeLastName        HoursWorked
1001            Mr          Peter                   Parker                  15,30,45
1002            Ms          Nancy                   Hall                    15,30,40

如果我能这样做,请告诉我?

1 个答案:

答案 0 :(得分:3)

使用FOR XML组合值:

SELECT
    E.EmployeeID,
    E.Title,
    E.FirstName,
    E.LastName,
    STUFF(
            (
                SELECT ',' + CONVERT(VARCHAR,HW.HoursWorked)
                FROM HoursWorked HW
                WHERE E.EmployeeId = HW.EmployeeId
                GROUP BY HW.HoursWorked
                ORDER BY HW.HoursWorked
                FOR XML PATH('')
            ), 1, 1, ''
         ) AS HoursWorked
FROM Employee E
GROUP BY E.EmployeeID,
         E.Title,
         E.FirstName,
         E.LastName