我在总帐管理系统中进行报告,该分类帐具有实际和预算金额的单独表格。我通过在子查询中将三个查询合并在一起并合并子查询的结果来合并数据。
我想知道是否有更好的方法可以做到这一点。
测试数据和查询如下。
-- 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
答案 0 :(得分:1)
您是否尝试过从实际到预算的完整外部联接?
http://psoug.org/snippet/FULL-JOIN-example-and-syntax_733.htm
答案 1 :(得分: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