2016-10-24 330 views
0

我有一個查詢努力回報經理的列表以及它們各自的員工T-SQL - 連接多個行

我有三個表如下:

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辛格

+0

搜索此:**在'SQL SERVER'模擬'GROUP_CONCAT' ** –

+0

@msinghm可以的東西,結果以逗號分隔的結果:http://stackoverflow.com/a/18870585/6812070 –

回答

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 
+0

謝謝大家,我現在得到了這個工作。你們都非常有幫助。 – msinghm

1

可以stuff結果以逗號分隔的結果。

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 
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)