通过将数据分组到不同的表中来收集数据?

时间:2019-05-17 09:01:25

标签: sql oracle

我有两个不同的表。 我将它们都归为一体。 两者都有两列。 因此,我想通过将两个表中的相同字段分组来收集这些字段中的数据。

示例;

mytable

salarytype    salary
Asalarytype   1000
Bsalarytype   2000
Csalarytype   3000

mytable2

salarytype    salary
Asalarytype   100
Bsalarytype   100
Csalarytype   100

我想要:1000 + 100 = 1100,2000 + 100 = 2100,3000 + 100 = 3100 ...

SELECT salarytype
,SUM(salary) FROM mytable GROUP BY salarytiype


SELECT salarytype
,SUM(salary) FROM mytable2 GROUP BY salarytiype

我想要达到的结果 ;

salarytype    totalsalary
Asalarytype    1100
Bsalarytype    2100
Csalarytype    3100
.
.
.

4 个答案:

答案 0 :(得分:1)

试试这个-

SELECT salarytype,SUM(Salary) 
FROM
(
    SELECT salarytype,Salary FROM MyTable
    UNION ALL
    SELECT salarytype,Salary FROM MyTable2
)A
GROUP BY salarytype    

答案 1 :(得分:0)

select salarytype,
       salary+(select salary from mytable2 where mytable2.salarytype== mytable.salarytype)
from mytable;

答案 2 :(得分:0)

这应该给您想要的结果-

WITH CTE AS 
(
    SELECT salarytype,
           salary 
    FROM MyTable

    UNION ALL

    SELECT salarytype,
           salary 
    FROM  MyTable2
)
SELECT salarytype,
       SUM(salary)
FROM CTE       
GROUP BY salarytype

答案 3 :(得分:0)

我认为您的表具有重复的值:因此您可以这样做

select distinct t1.salarytype, sum(t1.salary) from
(
select salarytype, sum(salary) from  mytable GROUP BY salarytype
UNION ALL
select salarytype, sum(salary) from  mytable2 GROUP BY salarytype
) t1
group by t1.salarytype, orderby t1.salarytype

##Hope this will resolve your problem, you can use distinct, to remove 
duplicates