将两个表合并为一个输出,并在不同列上分离

时间:2016-10-24 06:16:56

标签: sql sql-server sql-server-2014

初始数据示例:

 Project   | Status    |   Emp1     |   Emp2     |   Emp3     |
 --------------------------------------------------------------
 Project 1 |   Active  |     10     |     10     |     20     |
 Project 2 |   Closed  |     10     |     20     |     10     |
 Project 1 |   Closed  |     20     |     10     |     20     |
 Project 1 |   Active  |     20     |     20     |     10     |
 Project 2 |   Active  |     20     |     10     |     20     |

使用SQL Server 2014,我有2个查询,我需要将这些查询组合起来,根据状态将“1”按“项目”分组,并使用新的“Emp”列。

 SELECT [Project],
          SUM([Emp1]) as [Emp1_Act],                    
          SUM([Emp2]) as [Emp2_Act],
          SUM([Emp2]) as [Emp3_Act],
        from t where status = 'Active' 
 SELECT [Project],
          SUM([Emp1]) as [Emp1_Clo],                    
          SUM([Emp2]) as [Emp2_Clo],
          SUM([Emp2]) as [Emp3_Clo],
        from t where status = 'Closed'

请求的数据:

   Project   | Emp1_Act | Emp2_Act | Emp3_Act | Emp1_Clo | Emp2_Clo | Emp3_Clo |
   -----------------------------------------------------------------------------
   Project 1 |    30    |    30    |    30    |    10    |    20    |    10    |
   Project 2 |    20    |    10    |    20    |    20    |    10    |    20    |

1 个答案:

答案 0 :(得分:1)

因为您有固定数量的列,所以您应该可以使用标准数据透视查询:

SELECT Project,
       SUM(CASE WHEN Status = 'Active' THEN Emp1 ELSE 0 END) AS Emp1_Act,
       SUM(CASE WHEN Status = 'Active' THEN Emp2 ELSE 0 END) AS Emp2_Act,
       SUM(CASE WHEN Status = 'Active' THEN Emp3 ELSE 0 END) AS Emp3_Act,
       SUM(CASE WHEN Status = 'Closed' THEN Emp1 ELSE 0 END) AS Emp1_Clo,
       SUM(CASE WHEN Status = 'Closed' THEN Emp2 ELSE 0 END) AS Emp2_Clo,
       SUM(CASE WHEN Status = 'Closed' THEN Emp3 ELSE 0 END) AS Emp3_Clo
FROM t
GROUP BY Project