2012-06-19 74 views
0

我想寫一個SQL語句來獲取值的總和父內的所有兒童中包括一個輔助組的所有值:by子句

SELECT parent, child, sum(val) 
FROM table_a 
GROUP BY parent, child 
ORDER BY parent, child 

這是給我:

Parent1 Child1 123 
Parent1 Child2 456 
Parent2 Child1 789 
Parent3 Child1 12 
Parent3 Child2 345 

我想要的是讓所有的孩子,而不僅僅是每個父母的父母下方的孩子,如果它沒有記錄分配它的值爲0。例如:

Parent1 Child1 123 
Parent1 Child2 456 
Parent2 Child1 789 
Parent2 Child2 0 
Parent3 Child1 12 
Parent3 Child2 345 

我可以用GROUP BY子句做到這一點嗎?或者我需要使用子查詢?

回答

0

你將不得不自己交叉連接table_a,然後通過合成行進行組合。我不確定Oracle語法,否則我會寫一些實際的代碼。

0

您可以蠻力與在線欣賞問題,但是這可能是相當低效

SQL> ed 
Wrote file afiedt.buf 

    1 with t as (
    2 select 1 parent, 1 child, 123 val from dual union all 
    3 select 1, 2, 456 from dual union all 
    4 select 2, 1, 789 from dual union all 
    5 select 3, 1, 12 from dual union all 
    6 select 3, 2, 345 from dual 
    7 ) 
    8 select p.parent, c.child, nvl(sum(val),0) 
    9 from (select distinct parent from t) p 
10   cross join (select distinct child from t) c 
11   full outer join t on (t.parent = p.parent and t.child = c.child) 
12* group by p.parent, c.child 
SQL>/

    PARENT  CHILD NVL(SUM(VAL),0) 
---------- ---------- --------------- 
     2   1    789 
     1   2    456 
     3   1    12 
     1   1    123 
     2   2    0 
     3   2    345 

6 rows selected.