11

我想从 2 个不同的表中获取几列的总和(这些表共享相同的结构)。

如果我只考虑一张表,我会写这样的查询:

SELECT MONTH_REF, SUM(amount1), SUM(amount2)
    FROM T_FOO
    WHERE seller = XXX
    GROUP BY MONTH_REF;

但是,我还想使用表 T_BAR 中的数据,然后有一个select返回以下列的查询:

  • MONTH_REF
  • SUM(T_FOO.amount1) + SUM(T_BAR.amount1)
  • SUM(T_FOO.amount2) + SUM(T_BAR.amount2)

一切按 的值分组MONTH_REF

请注意,给定的记录MONTH_REF可以在一个表中找到,但不能在另一个表中找到。在这种情况下,我想得到T_FOO.amount1 + 0(或0 + T_BAR.amount1)的总和。

如何编写我的 SQL 查询来获取这些信息?

有关信息,我的数据库是 Oracle 10g。

4

5 回答 5

12

您可以在 group by 之前合并您的表(顺便说一下,这是在 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
于 2009-09-07T09:16:39.047 回答
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
于 2009-09-07T08:40:31.367 回答
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
于 2009-09-07T08:47:35.487 回答
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
于 2009-09-07T09:08:00.867 回答
-1
SELECT (SELECT SUM(amount) from debit) as debitamounts, (SELECT SUM(amount) from credit) as creditamounts
于 2015-11-25T16:17:26.937 回答