0

親内のすべての子の値の合計を取得する SQL ステートメントを作成しようとしています。

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 句でこれを行うことはできますか? または、サブクエリを使用する必要がありますか?

4

2 に答える 2

0

table_a をそれ自体でクロス結合してから、合成行全体でグループ化する必要があります。Oracle の構文についてはよくわかりません。それ以外の場合は、実際のコードを記述します。

于 2012-06-19T21:05:06.733 に答える
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.
于 2012-06-19T21:06:54.300 に答える