0

私は総勘定元帳からレポートを作成しています。総勘定元帳には、実績額と予算額の個別の表があります。サブクエリで 3 つのクエリを結合し、サブクエリの結果を合計することで、データをマージします。

これを行うためのより良い方法があるかどうか疑問に思っています。

テストデータとクエリは次のとおりです。

-- Create actuals table
create table actuals
(
gl_key number not null,
amount number not NULL
);

-- Create budgets table
create table budgets
(
gl_key number not null,
amount number not NULL
);
--add actuals data
INSERT INTO actuals (gl_key, amount) VALUES (300001000, 10000);
INSERT INTO actuals (gl_key, amount) VALUES (300002000, 50000);
INSERT INTO actuals (gl_key, amount) VALUES (300003000, 20000);
COMMIT;
--add budgets data
INSERT INTO budgets (gl_key, amount) VALUES (300001000, 7500);
INSERT INTO budgets (gl_key, amount) VALUES (300003000, 20000);
INSERT INTO budgets (gl_key, amount) VALUES (300004000, 5000);
COMMIT;
--merge query
WITH act_bud AS
(SELECT act.gl_key, act.amount AS act_amount, 0 AS bud_amount
FROM actuals act
LEFT OUTER JOIN budgets bud
ON act.gl_key = bud.gl_key
WHERE bud.gl_key IS NULL
UNION
SELECT bud.gl_key, 0 AS act_amount, bud.amount AS bud_amount
FROM budgets bud
LEFT OUTER JOIN actuals act
ON bud.gl_key = act.gl_key
WHERE act.gl_key IS NULL
UNION
SELECT act.gl_key, act.amount AS act_amount, bud.amount AS bud_amount
FROM actuals act
INNER JOIN budgets bud
ON act.gl_key = bud.gl_key)
SELECT gl_key, SUM(act_amount) AS act_amount, SUM(bud_amount) AS bud_amount
FROM act_bud
GROUP BY gl_key
ORDER BY gl_key

4

2 に答える 2

1

実績から予算への完全外部結合を試しましたか?

http://psoug.org/snippet/FULL-JOIN-example-and-syntax_733.htm

于 2013-05-23T03:30:11.940 に答える
0

これにより、クエリの管理がはるかに簡単になります。

SELECT nvl(act.gl_key, bud.gl_key) AS gl_key,
nvl(act.amount, 0) AS act_amount,
nvl(bud.amount, 0) AS bud_amount
FROM actuals act
FULL JOIN budgets bud
ON act.gl_key = bud.gl_key
ORDER BY 1

于 2013-05-23T04:19:09.427 に答える