如何针对Oracle编写此SQL?

时间:2012-06-15 04:25:07

标签: sql oracle

我有5张桌子:

TABLE_A:
    A_ID

TABLE_B:
    A_ID
    B_ID
TABLE_C:
    B_ID
    C_ID
    C_SOME_NUMBER

TABLE_D:
    A_ID
    D_ID
TABLE_E:
    D_ID
    E_ID
    E_SOME_NUMBER

如您所见,映射关系为:

1 A --> n B
1 B --> n C
1 A --> n D
1 D --> n E

我想编写一个SQL来计算:A_ID的计数:

sum(C_SOME_NUMBER) != sum(E_SOME_NUMBER)

但我不知道怎么写这个sql。我的数据库是Oracle

1 个答案:

答案 0 :(得分:2)

select
    count(Q1.ID) as 'whoopsie'
from
    (
        select
            a.ID,
            sum(c.some_number) as someNum
        from
            TA a,
            TB b,
            TC c
        where
            a.ID=b.IB
            and b.ID=c.ID
        group by
            a.ID
    ) Q1,
    (
        select
            a.ID,
            sum(e.some_number) as someNum
        from
            TA a,
            TD d,
            TE e
        where
            a.ID=d.IB
            and d.ID=e.ID
        group by
            a.ID
    ) Q2
where
    Q1.ID=Q2.ID
    and Q1.someNum != Q2.someNum