将两个SQL语句的结果合并为一个显示新结果的结果

时间:2015-11-05 17:16:02

标签: sql-server sql-server-2014

我有以下两个SQL语句(使用SQL Server 2014)

SELECT 
    EMP_CLASS_1
    ,SUM(TOT_MI/60) AS [Absent hours]
FROM [TestData].[dbo].[Absenteeism and SLWP TCS Data]
WHERE CODE = 'MLSKU' OR CODE = 'UNPDAB' OR CODE = 'UNPADH'
GROUP BY EMP_CLASS_1
ORDER BY EMP_CLASS_1

和第二个

SELECT 
    EMP_CLASS_1
    ,SUM(TOT_MI/60) AS [Schedule Hours]
FROM [TestData].[dbo].[Absenteeism and SLWP TCS Data]
WHERE code = 'attend'
GROUP BY EMP_CLASS_1
ORDER BY EMP_CLASS_1

我要做的是从第一个语句中取结果并将其除以第二个语句的结果。

到目前为止,我没有运气。

我非常环保,请耐心等待。

提前感谢您提供的任何帮助。

作为第二个问题,如果可能,我想在三个单独的专栏中一次显示所有三个结果。

2 个答案:

答案 0 :(得分:1)

假设两个查询之间有相应的行,您可以使用JOIN

WITH cte1 AS 
(
  SELECT EMP_CLASS_1
  ,SUM(TOT_MI/60) AS [Absent hours]
  FROM [TestData].[dbo].[Absenteeism and SLWP TCS Data]
  WHERE CODE IN('MLSKU' ,'UNPDAB' , 'UNPADH')
  GROUP BY EMP_CLASS_1
), cte2 AS
(
  SELECT EMP_CLASS_1
    ,SUM(TOT_MI/60) AS [Schedule Hours]
  FROM [TestData].[dbo].[Absenteeism and SLWP TCS Data]
  WHERE code = 'attend'
  GROUP BY EMP_CLASS_1
)
SELECT c1.EMP_CLASS_1
      ,c1.[Absent hours]
      ,c2.[Schedule Hours]
      ,[result] = c1.[Absent hours] / c2.[Schedule Hours]
FROM cte1 c1
JOIN cte2 c2
  ON c1.EMP_CLASS_1 = EMP_CLASS_1

甚至更简单:

SELECT EMP_CLASS_1
   ,SUM(IIF(CODE IN('MLSKU' ,'UNPDAB' , 'UNPADH'), TOT_MI, 0)  /60) AS [Absent hours]
   ,SUM(IIF(CODE ='attend', TOT_MI, 0) /60) AS [Schedule Hours]
   ,SUM(IIF(CODE IN('MLSKU' ,'UNPDAB' , 'UNPADH'), TOT_MI, 0)  /60) 
    / SUM(IIF(CODE ='attend', TOT_MI, 0) /60) AS [result]
FROM [TestData].[dbo].[Absenteeism and SLWP TCS Data]
WHERE CODE IN ('MLSKU' ,'UNPDAB' , 'UNPADH','attend')
GROUP BY EMP_CLASS_1
ORDER BY EMP_CLASS_1;

答案 1 :(得分:0)

由于您要查询同一个表并按同一列进行分组,因此可以通过加入where子句来实现此目的,以便它们包含两组相关行并应用sum case声明原始条件。

请注意,顺便说一下,使用where运算符可以更优雅地编写第一个查询的in子句:

SELECT   emp_class_1, 
         SUM(CASE WHEN code IN ('MLSKU', 'UNPDAB', 'UNPADH') THEN tot_mi/60 END) /
         SUM(CASE code WHEN 'attend' THEN tot_mi/60 END)
FROM     [TestData].[dbo].[Absenteeism and SLWP TCS Data]
WHERE    code IN ('MLSKU', 'UNPDAB', 'UNPADH', 'attend') 
GROUP BY emp_class_1
ORDER BY emp_class_1