基于Oracle中其他列的不同值的列总和

时间:2016-11-21 12:52:35

标签: oracle

表A

A1 A2
1  7
2  8
1  9

表B

A1 B2
1  2
2  3  

我想要这样的东西

select A.A1,sum(case when distinct A.A1 then B2),sum(A.A2) from
A,B
where A.A1=B.A1(+)
group by A.A1

加入我的表后将

A1  A2  B2
1   7   2
2   8   3
1   9   2

结果表

A1  A2    B2
1   7+9   2(only once)
2   8     3

如上所述,如何在加入表格后获得不同A1的B2总和。 提前致谢

2 个答案:

答案 0 :(得分:0)

使用JOINGROUP BY

<强>查询

SELECT t1.A1, SUM(t1.A2) AS A1, SUM(t2.B2) AS B2
FROM TableA t1
JOIN TableB t2
ON t1.A1 = t2.A1
GROUP BY t1.A1;

答案 1 :(得分:0)

由于table_b.a1是唯一的,因此最好的方法是先计算table_a.a2的总和,以减少你加入的行数,然后加入table_b。那么你不必担心总结不同的table_b.b2值,否则你将不得不这样做。

WITH table_a AS (SELECT 1 a1, 7 a2 FROM dual UNION ALL
                 SELECT 2 a1, 8 a2 FROM dual UNION ALL
                 SELECT 1 a1, 9 a2 FROM dual),
     table_b AS (SELECT 1 a1, 2 b2 FROM dual UNION ALL
                 SELECT 2 a1, 3 b2 FROM dual)
-- end of mimicking your two tables with sample_data in them;
-- see the sql below:
SELECT ta.a1,
       ta.a2,
       tb.b2
FROM   (SELECT   a1, SUM(a2) a2
        FROM     table_a
        GROUP BY a1) ta
       INNER JOIN table_b tb ON ta.a1 = tb.a1;

        A1         A2         B2
---------- ---------- ----------
         1         16          2
         2          8          3

如果你绝对必须首先加入这两个表(我不建议这样做,这对数据库做了更多的工作),那么你可以这样做:

WITH table_a AS (SELECT 1 a1, 7 a2 FROM dual UNION ALL
                 SELECT 2 a1, 8 a2 FROM dual UNION ALL
                 SELECT 1 a1, 9 a2 FROM dual),
     table_b AS (SELECT 1 a1, 2 b2 FROM dual UNION ALL
                 SELECT 2 a1, 3 b2 FROM dual)
SELECT   ta.a1,
         SUM(ta.a2) a2,
         MAX(tb.b2) b2
FROM     table_a ta
         INNER JOIN table_b tb ON ta.a1 = tb.a1
GROUP BY ta.a1;

        A1         A2         B2
---------- ---------- ----------
         1         16          2
         2          8          3

由于table_b.b2每个table_a.a1只能有一个不同的值,我们可以通过MAX选择一个要使用的值(我们可以使用MIN或{{1而不是,fyi)。