在SQL中按列分组

时间:2016-11-14 06:04:39

标签: sql sql-server

我有一个名为 EmpTBL 的Sql表,它由数据组成:

ID  Emp_ID  Dept    Role_ID Status  
82  E00004  D1       3        1        
82  E00004  D2       3        1
83  E00034  E2       1        1 
84  E00043  G1       2        1 
84  E00043  G2       2        1 
84  E00043  G3       2        1 
76  E01053  A1       1        1 

我需要编写一个查询,将Emp_ID分组并将Dept显示为

ID  Emp_ID  Dept       Role_ID  Status
82  E00004  D1, D2      3        1
83  E00034  E2          1        1
84  E00043  G1, G2, G3  2        1
76  E01053  A1          1        1

2 个答案:

答案 0 :(得分:3)

    CREATE TABLE #EmpTbl(ID INT, Emp_ID VARCHAR(100), Dept VARCHAR(100),Role_ID INT, Status INT)

    INSERT INTO  #EmpTbl(ID , Emp_ID , Dept ,Role_ID , Status )
    SELECT 82,'E00004','D1',3,1 UNION ALL         
    SELECT 82,'E00004','D2',3,1 UNION ALL 
    SELECT 83,'E00034','E2',1,1 UNION ALL  
    SELECT 84,'E00043','G1',2,1 UNION ALL  
    SELECT 84,'E00043','G2',2,1 UNION ALL  
    SELECT 84,'E00043','G3',2,1 UNION ALL  
    SELECT 76,'E01053','A1',1,1 

    SELECT DISTINCT T1.ID,T1.Emp_ID,A.Dept,T1.Role_ID,T1.Status
    FROM #EmpTbl T1
    JOIN
    (
    SELECT Emp_ID ,STUFF((SELECT ',' + Dept FROM #EmpTbl T3 WHERE T3.Emp_ID = T2.Emp_ID 
    FOR XML PATH('')),1,1,'') Dept
    FROM #EmpTbl T2
    GROUP BY Emp_ID 
    ) A ON A.Emp_ID = T1.Emp_ID'

答案 1 :(得分:0)

试试这个:

SELECT ID, Emp_ID, Dept = STUFF((SELECT ', ' + Dept 
  FROM EmpTBL AS e2
   WHERE e2.Emp_ID = e1.Emp_ID 
   ORDER BY Dept
   FOR XML PATH('')), 1, 1, ''), Role_ID, Status
FROM EmpTBL AS e1
GROUP BY Emp_ID
ORDER BY Emp_ID