用于将一个父项连接到三个子表的SQL语句

时间:2014-08-31 19:55:56

标签: sql vba excel-vba ms-access-2010 excel

我有一个应用程序,它有一个父表和三个子表。为了论证,我们可以调用表Parent,Child1,Child2和Child3。表格包含以下列:

Parent: Key, Desc
Child1: Key, ParentKey, Date, AccessCount
Child2: Key, ParentKey, Date, AssceeCount
Child3: Key, ParentKey, Date, AccessCount

我试图在Visual Basic中创建一个SQL查询,对于指定的Parent.Key范围,它将给我Sum(Child1.AccessCount)作为Child1-Total,Sum(Child2.AccessCount)作为Child2-Total,Sum (Child3.AccessCount)作为Child3-Total,用于指定的日期范围。

我希望输出看起来像这样:

ParentKey ParentDesc Child1-Total Child2-Total Child3-Total

到目前为止,我已经尝试了以下Visual Basic SQL语句:

Select Parent.Key as [ParentKey], Parent.Desc as [ParentDesc],
   Sum(Child1.AccessCount) as [Child1-Total],
   Sum(Child2.AccessCount) as [Child2-Total],
   Sum(Child3.AccessCount) as [Child2-Total],
From ((Parent
   Inner Join Child1 On (Parent.Key = Child1.ParentKey
                     And Child1.Date >= #01/01/2013#
                     And Child1.Date <= #31/12/2014#))
   Inner Join Child2 On (Parent.Key = Child2.ParentKey
                     And Child2.Date >= #01/01/2013#
                     And Child2.Date <= #31/12/2014#))
   Inner Join Child3 On (Parent.Key = Child3.ParentKey
                     And Child3.Date >= #01/01/2013#
                     And Child3.Date <= #31/12/2014#)
Where Parent.Key >=5 And Parent.Key <= 25
Group By Parent.Key, Parent.Desc

我的Visual Basic SQL语句产生不正确的结果,所以我希望有人指出我正确的方向并帮助我生成SQL,这将给出正确的结果。注意:我知道上面的语句无效VB因为&#34;行继续&#34;不见了。

提前感谢您的协助。

1 个答案:

答案 0 :(得分:0)

使用子查询进行聚合。假设您正在使用MS Access,则查询类似于:

select p.key, nz(cnt1, 0) + nz(cnt2, 0) + nz(cnt3, 0)
from (((parent as p left join
        (select parentkey, sum(accesscount) as cnt1
         from child1
         where Child1.Date >= #01/01/2013# And Child1.Date <= #31/12/2014#
        ) as c1
        on c1.parentkey = p.key
       ) left join
       (select parentkey, sum(accesscount) as cnt2
        from child2
        where Child2.Date >= #01/01/2013# And Child2.Date <= #31/12/2014#
       ) as c2
       on c2.parentkey = p.key
      ) left join
      (select parentkey, sum(accesscount) as cnt3
       from child3
       where Child3.Date >= #01/01/2013# And Child3.Date <= #31/12/2014#
      ) as c3
      on c2.parentkey = p.key;

编辑:

我没有意识到MS Access不允许from子句中的子查询 - 更有理由改为另一个数据库。

您可以使用select

中的相关子查询执行此操作
select p.key,
       nz( (select sum(accesscount) 
            from child1
            where Child1.Date >= #01/01/2013# And Child1.Date <= #31/12/2014# and
                  Child1.parentkey = p.key
           ), 0) as cnt1,
       nz( (select sum(accesscount)
            from child1
            where Child2.Date >= #01/01/2013# And Child2.Date <= #31/12/2014# and
                  Child2.parentkey = p.key
           ), 0) as cnt2,
       nz( (select sum(accesscount)
            from child3
            where Child3.Date >= #01/01/2013# And Child3.Date <= #31/12/2014# and
                  Child3.parentkey = p.key
           ), 0) as cnt3
from parent as p;