根据两个表计算sal的总和

时间:2013-10-25 10:58:46

标签: postgresql

两个表格,如

table1

+----+-------+-----+
| id | sname | sal |
+----+-------+-----+
|  1 | X     | 100 |
|  2 | Y     | 200 |
|  3 | Z     | 400 |
+----+-------+-----+

表2

+----+-------+-----+
| id | sname | sal |
+----+-------+-----+
|  1 | A     | 500 |
|  2 | B     | 200 |
|  3 | C     | 400
|  4   A       100
+----+-------+-----+

这两个表都有关系发货列号

我需要通过table1.sname计算总和sal组,同时与table2匹配

输出如

+-------+-------+---------------------
| Table1.sname | Table2.sname   | sum |
+-------+-------+-----+ ----------------
| A         | W         | 600 |
| B         | Y         | 200 |
| B         | F         | 300 |
| C         | Z         | 400 |
+-------+-------+----------------------



select sum(sal),a.sname,b.sname 
from table1 a,
     (select id,sname from table2 group by sname,id) as b 
where a.id=b.id 
group by a.sname,b.sname;

但没有给出正确的o / p

1 个答案:

答案 0 :(得分:1)

你的问题有点模棱两可......但也许你想要这个。

查询

select Table11.id, Table1.sname, Table2.sname, (Table1.sal+Table2.sal) as Sum
from Table1, Table2
where Table1.id = Table2.id;

结果

 Table1.id | Table2.sname | Table2.sname | sum
-----------+--------------+--------------+-----
         1 | a            | d            | 500
         2 | b            | e            | 700
         3 | c            | f            | 900