2012-07-07 56 views
1

我有我的表的下方设计: -Oracle组加入


Table A 
-------------------------- 
subCatId | catId | catDesc 
-------------------------- 
    1  | 3 | 100 
    2  | 3 | 100 
    3  | 5 | 100 
    4  | 5 | 100 
    5  |  | 100 

Table B 
-------------------------- 
subCatId | amount 
-------------------------- 
    1  | 10 
    2  | 20 
    3  | 5 
    4  | 15 
    5  |  

第三个表,即表AB,是一个地方的记录将被插入。在上述表格的基础上,查询应该: 1.检查表格AB,是否存在任何subCatId。 2.如果该表为空,则获取catDes表中存在catDesc = 100且基于表A的subCatId的表B的数量的所有subCatId & catId。


Table AB 
-------------------------- 
subCatId | catId | amount 
-------------------------- 
    1  | 3 | 10 
    2  | 3 | 20 
    3  | 5 | 35  
    4  | 5 | 15 
    5  |  | 50  

正如你可以看到上面的表AB为subCatId 1 & 2 CATID是3,从而对1 & 2应总结并示出了用于subCatId 3(包括量值5,其已经是量的值在表B中)。相似地,对于subCatId 5,金额值应该从subCatId 3 & 4.

我真的很感谢,如果有人能够帮助我获得如上所示的TableAB预期结果。

我曾尝试下面的查询分别

SELECT A.CATID, SUM(B.AMOUNT) 
FROM A LEFT OUTER JOIN B 
      ON A.SUBCATID = B.SUBCATID 
WHERE A.CATDESC=100 
    AND A.SUBCATID NOT IN 
      (SELECT AB.SUBCATID FROM AB) 
GROUP BY CATID; 

但是,它只给CATID和总量值,但我无法找到一个办法让subCatId和它们各自的量也。请帮助...谢谢。应用左外连接的原因是,如果表B中不存在subCatId,但它存在于表A中,那么它也应该与结果一起显示。

+0

我已经单独尝试了下面的查询“SELECT A.CATID,SUM(B.AMOUNT)FROM LEFT OUTER JOIN B ON A.SUBCATID = B.SUBCATID WHERE A.CATDESC = 100 AND A.SUBCATID NOT IN(SELECT AB.SUBCATID FROM AB)GROUP BY CATID;“。然而,它只给出了catid和总金额值,但我无法找到获得子金额及其各自金额的方法。请帮助...谢谢。应用左外连接的原因是,如果表B中不存在subCatId,但它存在于表A中,那么它也应该与结果一起显示。 – SteveM 2012-07-07 16:53:17

回答

1

这个解释很接近,但并没有完全得到你想要的。

首先,先从量的基表:

select a.subcatid, a.catid, b.amount 
from (select * 
     from A 
     where a.catdesc = 100 
    ) A left outer join 
    B 
    on a.subcatid = b.subcatid left outer join 
    AB 
    on a.subcatid = ab.subcatid and a.catid = b.catid 
where ab.subcatid is null 

接下来,你要在这里走量,并添加从哪里CATID等于SUBCAT ID的所有金额。要做到这一点,我们需要一个自我加入。我将使用语法将其定义为一个别名:

with t as (
    select a.subcatid, a.catid, b.amount 
    from (select * 
      from A 
      where a.catdesc = 100 
     ) A left outer join 
      B 
      on a.subcatid = b.subcatid left outer join 
      AB 
      on a.subcatid = ab.subcatid and a.catid = b.catid 
    where ab.subcatid is null 
) 
select t.subcatid, t.catid, 
     (t.amount + coalesce(tcat.amount, 0)) as amount 
from t left outer join 
    (select catid, sum(amount) as amount 
     from t 
     group by catid 
    ) tcat 
    on t.subcatid = t.cat 

的问题是,这个总结的基础金额,而不是沿途的中间总计。因此,“5”的总数包括“3”和“4”的基数,但不包括它们下面的小计。

为了获得完整的解决方案,您似乎需要两件事之一。要么建立一个循环来逐行浏览表格,使用更新和查询来获得你所需要的。或者,我认为甲骨文有“connect by”语句,它允许沿着树结构进行查询。不幸的是,我不太清楚产生正确的SQL。或者,如果树结构不太深 - 比如在你的例子中 - 那么你可以手动遍历一个或两个级别,如果这足够的话。

+0

感谢Gordon的回答。我已经得到了你所提到的结果。你是对的,我必须逐行循环遍历表格,以便更新总量。我相信它只是我留下的最佳解决方案。再次感谢您的指导。 – SteveM 2012-07-09 14:18:25