将查询结果除以另一个查询的结果

时间:2012-02-07 12:25:24

标签: sql sql-server-2008

我有一个SQL-Sever查询,它返回在任何特定日期可供个人使用的容量。 结果将根据该人在该特定日期计划的每项任务返回。

我的问题是,它会在查询结果的每一行返回当天的总容量。 因此,当您显示一个人在一天内的所有结果时,在excel中的链接数据透视表中(例如),您将获得记录数乘以基本容量。

我写了另一个查询,计算每人每天的作业数量。

我想将第一个查询的容量除以第二个查询返回的记录数,但不知道如何将查询连接在一起。

这是一个按天返回分配列表的查询:

SELECT 
  MSP_EpmAssignmentByDay.TimeByDay, 
  MSP_EpmAssignment.ResourceUID, 
  MSP_EpmAssignmentByDay.AssignmentActualWork, 
  MSP_EpmResourceByDay_UserView.Capacity
FROM 
  MSP_EpmAssignment MSP_EpmAssignment,      
  MSP_EpmAssignmentByDay MSP_EpmAssignmentByDay,
  MSP_EpmResourceByDay_UserView
  MSP_EpmResourceByDay_UserView
WHERE   
  MSP_EpmAssignmentByDay.AssignmentUID = MSP_EpmAssignment.AssignmentUID 
  AND MSP_EpmResourceByDay_UserView.TimeByDay = MSP_EpmAssignmentByDay.TimeByDay

这是一个返回每人每天分配数量的查询:

SELECT 
  count(TimeByDay) as DayCount 
FROM 
  MSP_EpmAssignmentByDay_UserView 
  LEFT JOIN MSP_EpmAssignment_UserView
  ON MSP_EpmAssignmentByDay_UserView.AssignmentUID =
     MSP_EpmAssignment_UserView.AssignmentUID
GROUP BY ResourceUID, TimeByDay 

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:1)

假设您需要的唯一字段是查询中包含的字段,请尝试:

SELECT 
  MSP_EpmAssignmentByDay.TimeByDay, 
  MSP_EpmAssignment.ResourceUID, 
  SUM(MSP_EpmAssignmentByDay.AssignmentActualWork) TotalWork, 
  MAX(MSP_EpmResourceByDay_UserView.Capacity) Capacity
FROM 
  MSP_EpmAssignment,      
  MSP_EpmAssignmentByDay,
  MSP_EpmResourceByDay_UserView
WHERE   
  MSP_EpmAssignmentByDay.AssignmentUID = MSP_EpmAssignment.AssignmentUID 
  AND MSP_EpmResourceByDay_UserView.TimeByDay = MSP_EpmAssignmentByDay.TimeByDay
GROUP BY
  MSP_EpmAssignmentByDay.TimeByDay, 
  MSP_EpmAssignment.ResourceUID

或者,尝试将数据透视表中Capacity的摘要操作更改为MAX而不是SUM。

编辑:要在详细信息中包含相同ResourceUID和TimeByDay的记录计数,请尝试:

SELECT 
  MSP_EpmAssignmentByDay.TimeByDay, 
  MSP_EpmAssignment.ResourceUID, 
  MSP_EpmAssignmentByDay.AssignmentActualWork, 
  MSP_EpmResourceByDay_UserView.Capacity,
  count(*) over (partition by MSP_EpmAssignmentByDay.TimeByDay,
                              MSP_EpmAssignment.ResourceUID) DayCount
FROM 
  MSP_EpmAssignment MSP_EpmAssignment,      
  MSP_EpmAssignmentByDay MSP_EpmAssignmentByDay,
  MSP_EpmResourceByDay_UserView
  MSP_EpmResourceByDay_UserView
WHERE   
  MSP_EpmAssignmentByDay.AssignmentUID = MSP_EpmAssignment.AssignmentUID 
  AND MSP_EpmResourceByDay_UserView.TimeByDay = MSP_EpmAssignmentByDay.TimeByDay