T-SQL - 连接多行

时间:2016-10-24 15:06:36

标签: sql rows concat

我正在努力查询以返回与各自员工一起的经理列表

我有三张表如下:

Managers
ManagerID   ManagerName
1           Bob
2           Sally
3           Peter
4           George

EmployeeManager
EmployeeID  ManagerID
1           1
1           1
2           2
2           2
3           3
3           3
4           4
4           4

Employees
EmployeeID  EmployeeName
1           David
1           Joseph
2           Adam
2           Pete
3           Mark
3           Mavis
4           Susan
4           Jennifer

所需的结果集

ManagerName CountEmployee   Employees
Bob          2              David, Joseph
Sally        2              Anish, Pete
Peter        2              Mark, Mavis
George       2              Susan, Jennifer

我目前使用的查询如下:

Select m.ManagerName 
        ,Count(e.EmployeeName) Over(Partition By m.ManagerID) as CountEmployee 
        ,Rank() Over(Partition By m.ManagerID Order By em.EmployeeID) [RankEmployee]
       ,e.EmployeeName
From dbo.Employees e
Left Join dbo.EmployeeManager em on em.ManagerID=e.ManagerID
Left Join dbo.Managers m on m.ManagerID=em.ManagerID;

这将返回各行的经理和员工列表,但我很难按照上表连接员工姓名。

任何想法或解决方案?

Manpaal Singh

3 个答案:

答案 0 :(得分:1)

您可以 Select m.ManagerName ,Count(e.EmployeeName) Over(Partition By m.ManagerID) as CountEmployee ,Rank() Over(Partition By m.ManagerID Order By em.EmployeeID) [RankEmployee] ,STUFF((SELECT ',' + e.EmployeeName FOR XML PATH('')), 1, 1, '') AS EmployeeName From dbo.Employees e Left Join dbo.EmployeeManager em on em.ManagerID=e.ManagerID Left Join dbo.Managers m on m.ManagerID=em.ManagerID 结果以逗号分隔结果。

{{1}}

答案 1 :(得分:0)

SELECT M.ManagerName, E.EmployeeName 
FROM Managers AS M
INNER JOIN EmployeeManager AS EM ON M.ManagerID = EM.ManagerID
INNER JOIN Employees AS E ON EM.EmployeeID = E.EmployeeID
ORDER BY M.ManagerName

这将列出经理及其员工。 当你修复员工表的ID时。

1       David
1       Joseph
2       Adam
2       Pete
3       Mark
3       Mavis
4       Susan
4       Jennifer

应该是:

1       David
2       Joseph
3       Adam
4       Pete
5       Mark
6       Mavis
7       Susan
8       Jennifer

答案 2 :(得分:0)

您可以使用递归sql转换字符串中的行:

with t1 (mngId, empName) as (
    select a.mngId,
           b.empname
    from manager as a, employee as b
    where b.mngId = a.mngId),
t2 (mngID, nbr, empName, all_name) as (
    select mngId, 
        cast(1 as Int), 
        min(empName), 
        cast(min(empName) as varchar(1000)
    from t1 
    group by mngId
    union all
    select b.mngId,
        b.nbr+1,
        a.empName,
        trim(b.all_name) concat ', ' concat a.empName
    from t0 as a, t1 as b
    where b.mngId = a.mngId
        and a.empName > b.empName
        and a.empName = (
            select min( c.empName)
            from t0 as c
            where c.mngId = b.mngId
                and c.empName > b.empName )
)
select * 
from t1 as e
where nbr = ( 
    select max(nbr) 
    from t1 as d
    where d.mngId = e.mngId )