如何避免在这种情况下使用子查询Access SQL

时间:2014-06-19 20:30:28

标签: sql ms-access-2007

您好我需要加入两个表但从第三个表中过滤值。如下:

SELECT a.Key , (SELECT SUM(B.hours) FROM tableB as B 
                 INNER JOIN tableC as C ON B.List=C.List 
                 WHERE C.Status = 'Approved' AND B.Key LIKE A.key) , 
               (SELECT SUM(B.hours) FROM tableB as B 
                 INNER JOIN tableC as C ON B.List=C.List 
                 WHERE C.Status = 'Pending' AND B.Key LIKE A.key) 
FROM tableA as A GROUP BY A.key

还有另一种方法可以在不使用相关子查询的情况下执行此操作吗?我想使用连接,但我不知道如何将表格C链接到这张图片中。

提前致谢。

1 个答案:

答案 0 :(得分:2)

子查询可能不是一个坏主意,但你可以用条件聚合来做到这一点:

SELECT a.Key,
       sum(iif(c.Status = "Approved", B.hours, 0)),
       sum(iif(c.Status = "Pending", B.hours, 0))
FROM tableA as A left join
     (tableB as b inner join
      tableC as c
      on b.list = c.list
     ) 
     on b.key like a.key
GROUP BY A.key;

MS Access具有用于连接的神秘语法,特别是对于多个连接。我认为以上是正确的。