数据结果的数学从两个独立的非交叉表中提取

时间:2015-01-15 19:36:54

标签: sql sql-server

目标是使用下面的表字段信息,在每个表的一个字段上执行不同的计算(table1字段1的总和,计数table2字段2),然后将每个单独计算的结果除以得到"结果&#34 ; (见下面的等式)。

问题是我的SQL语句总是只计算两个表中常见的Employees。例如,对于340名员工,Table2,其中来自table1的培训时间超过日期范围= 18,"结果"应该是18/340 = .05,但对于我的SQL语句,它只能看到340名员工中的3名,因此它给出并回答了18/3 = 6.我想要计算表2中的所有员工,无论日期范围和table1,然后在日期范围内独立地计算表1中的小时数,然后将这两个独立的结果(小时/计数)除以得到最终的结果"。

表/字段信息:

table1 = Training_Action_SPPAL (sub table of All_Actions table)
table1 field1 = double1
table1 field2 = date1  (date1 range filter = 10/01/2014 to 09/30/2015)


table2 = Employee
table2 field1 = name

等式:

sum(double1)/count(name) = "result" over date range of date1

单个SQL语句的示例数据独立运行:

sum(double1) = 420.5    
count(name) = 380    
result = 1.1  (hand calculated, but SQL below resulted in 2.7)

有效的SQL却产生了错误的结果:

SELECT (SUM(a.double1)) / (COUNT(name))
FROM all_actions a, employee
WHERE a.category='Training_Action_SPPAL'
  AND a.date1 BETWEEN '10/01/2014' AND '09/30/2015'

1 个答案:

答案 0 :(得分:0)

我会将值分成两个查询:

SELECT (SELECT Sum(double1) FROM all_actions 
  WHERE category='Training_Action_SPPAL' AND date1 between '10/01/2014' and '09/30/2015') / 
(SELECT Count(*) FROM Employee) AS Result