将两个查询合并为一个GROUP BY和SUM one属性

时间:2015-01-16 13:19:02

标签: ms-access access-vba ms-access-2007

我有一个数据库应用程序来管理项目及其资源(=员工)。我的概述显示了所有员工,他们被分配到的项目以及他们被分配到该项目的小时数。

概述包含两个查询(记录集),这些查询在VBA代码的循环中放在一起。

  1. 查询,rstEmployees:
  2. SELECT employeeID, employeeName, SUM(janPlan), First(janRest), ... , SUM(decPlan), FIRST(decRest) 
    FROM tblRessources 
    INNER JOIN tblEmployees ON employeeID = employeeID
    GROUP BY employeeID, employeeName
    

    为每位员工循环。在每个循环中,员工的所有对应项目都在临时表中读取和写入。我使用以下查询:

    1. query,rstRessources
    2. SELECT projectName, janPlan, janRest, ... , decPlan, decRest
      FROM tblRessources
      INNER JOIN tblProjects ON projectID = projectID
      WHERE employeeID = rstEmployees(employeeID)
      
      • 计划:分配给项目的小时数
      • 休息:空闲时数

      我想要的结果是一个连续的形式,如下所示:

      Overview
      此过程耗时太长(最多30秒),我只想使用SQL查询或数据透视表执行此操作。我想摆脱循环,因为这需要太多时间。这甚至只能用SQL吗?你对如何实现这个有什么想法吗?

      如果它以任何方式有所帮助,那么更改基础表是可能的。此外,我知道这些表违反了原子性和所有良好的规范化内容,但它适用于我当前的解决方案。

      感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

select r.level,case when r.level=0 then r.employeeName when r.level=1 then r.projectName end name,r.janPlan 
from 
(
    select 0 level,e.employeeID,e.employeeName,0 projectID,'' projectName,SUM(r.janPlan) janPlan
    from tblRessources r
    join tblEmployees e ON e.employeeID = r.employeeID
    group by e.employeeID,e.employeeName
    union all
    select 1 level,e.employeeID,e.employeeName,p.projectID,p.projectName,SUM(r.janPlan) janPlan
    from tblRessources r
    join tblEmployees e ON e.employeeID = r.employeeID
    join tblProjects p ON p.projectID = r.projectID
    group by e.employeeID,e.employeeName,p.projectID,p.projectName
) r
order by r.employeeName,r.projectName

结果如下所示: enter image description here

答案 1 :(得分:0)

iBener给了我解决问题的决定性线索。我将他的MYSQL查询翻译成了access-SQL,这个可以工作:

SELECT employeeID, 
SWITCH(typ = 0, 'typ 0', typ = 1, 'typ 1') AS typSwitch, 
SWITCH(typ = 0, employeeName, typ = 1, projektName) AS employeeProjekt, rankName,
SumJanPlan, FJanRest

FROM( 
SELECT 0 AS typ, ma.employeeName, NULL AS projektName, ma.dKX, 
  ma.employeeName, ma.employeeName AS rankName,
  SUM(janPlan) AS SumJanPlan, FIRST(janRest) AS fJanRest
FROM tblEmployees AS ma LEFT JOIN tblRessourcs AS res ON ma.dKX = res.dKX
WHERE res.jahr = 2015
GROUP BY ma.employeeName, ma.dKX

UNION ALL

SELECT 1 AS typ, NULL AS employeeName, pro.projektName, res.dKX, 
  ma.employeeName AS rankName, SUM(janPlan) AS SumJanPlan, FIRST(janRest) AS fJanRest
FROM tblProjekte AS pro 
  INNER JOIN (tblEmployees AS ma 
  INNER JOIN tblRessources AS res ON ma.employeeID = res.employeeID) ON pro.projektNr = res.projektNr

WHERE res.[jahr]=2015 AND res.employeeID IN (
  SELECT DISTINCT employeeID FROM tblRessources
  WHERE jahr = 2015) 
GROUP BY pro.projektName, ma.employeeName, res.dkx)

ORDER BY rankName, typ

请注意

  • 我不得不添加一个额外的nameRank列以便全部 员工按字母顺序显示。否则订单是 由employeeID决定。
  • level是Access-SQL中的保留字,所以我使用了typ
  • 使用SWITCH(IF,THEN,ESLE IF,THEN,......)而不是CASE

干杯!