0

我确实从我们的总帐中报告,其中有单独的表格用于实际和预算金额。我通过在一个子查询中将三个查询合并在一起并对子查询的结果求和来合并数据。

我想知道是否有更好的方法来做到这一点。

测试数据和查询如下。

-- 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 回答