我想从两个不同的表中获得几列的总和(这些表共享相同的结构)。
如果我只考虑一个表,我会写这种查询:
SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF;
但是,我还想使用表T_BAR中的数据,然后使用select
查询返回以下列:
所有内容均按MONTH_REF
的值分组。
请注意,给定MONTH_REF
的记录可以在一个表中找到,但不能在另一个表中找到。
在这种情况下,我希望获得T_FOO.amount1 + 0
(或0 + T_BAR.amount1
)的总和。
如何编写SQL查询以获取此信息?
有关信息,我的数据库是Oracle 10g。
答案 0 :(得分:12)
您可以在组之前将表联合起来(顺便说一下,这是在Oracle上):
SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
FROM (SELECT month_ref, amount1, amount2
FROM T_FOO
WHERE seller = XXX
UNION ALL
SELECT month_ref, amount1, amount2
FROM T_BAR
WHERE seller = XXX
) t
GROUP BY t.month_ref
您也可以将表与卖家字段合并,稍后再过滤(如果您需要更高级的逻辑):
SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
FROM (SELECT month_ref, amount1, amount2, seller
FROM T_FOO
UNION ALL
SELECT month_ref, amount1, amount2, seller
FROM T_BAR) t
where t.seller = XXX
GROUP BY t.month_ref
答案 1 :(得分:2)
您是否尝试过使用工会?
SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM (
SELECT MONTH_REF, SUM(amount1) AS amount1, SUM(amount2) as amount2
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF
UNION ALL SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_BAR
WHERE seller = XXX
GROUP BY MONTH_REF
) tmp
GROUP BY MONTH_REF
答案 2 :(得分:1)
或者,外部联接也应该起作用:
SELECT month_ref,
SUM(t_foo.amount1) + SUM(t_bar.amount1),
SUM(t_foo.amount2)+SUM(t_bar.amount2)
FROM t_foo FULL OUTER JOIN t_bar
ON t_foo.month_ref = t_bar.month_ref
GROUP BY month_ref
答案 3 :(得分:1)
我终于使用Lieven的答案来解决这个问题了。
以下是正确的代码(amount1 = ...
无法在我的环境中运行,并且查询中的;
太多了:
SELECT MONTH_REF, SUM(sumAmount1), SUM(sumAmount2)
FROM (
SELECT MONTH_REF, SUM(amount1) as sumAmount1, SUM(amount2) as sumAmount1
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF
UNION ALL SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_BAR
WHERE seller = XXX
GROUP BY MONTH_REF
) tmp
GROUP BY MONTH_REF
答案 4 :(得分:-1)
SELECT (SELECT SUM(amount) from debit) as debitamounts, (SELECT SUM(amount) from credit) as creditamounts