用于从两个表中查找总和的SQL查询

时间:2014-10-10 12:50:04

标签: mysql sql sql-server postgresql mysqli

我有两个表都有序列ID来识别相应的行。但是,一个表以一对多的形式具有数据条目,而另一个表以一对一的形式具有数据。我需要找到与特定序列ID相对应的值的总和。

表格就像

表1

seq_id      amt1      amt2
  222        0         100 
  223        0         200
  224       300         0

表2

seq_id     code       amt3
 222        001        100
 222        002        150
 223        001        100

我需要从两个表中找到相应ID的amt1 + amt2 + amt3的总和

即输出可能看起来像

TOTAL_AMOUNT
850

6 个答案:

答案 0 :(得分:2)

这将显示table1

中显示的所有seq_id值的总和
select t1.seq_id, sum(t1.amt1 + t1.amt2 + coalesce(t2.amt3)) as total_amount
from table1 t1
  left join table2 t2 on t1.seq_id = t2.seq_id
group by t1.seq_id;

如果table2中的seq_id值在table1中,则需要完全外部联接。在这种情况下,您还需要处理t1中的空值:

select t1.seq_id, sum(coalesce(t1.amt1,0) + coalesce(t1.amt2,0) + coalesce(t2.amt3)) as total_amount
from table1 t1
  full join table2 t2 on t1.seq_id = t2.seq_id
group by t1.seq_id;

如果要独立于其seq_id对所有值求和,请使用union:

select sum(amount) as total_amount
from (
   select amt1 + amt2 as amount
   from table1
   union all
   select amt3 as amount
   from table2
) t

答案 1 :(得分:1)

一些嵌套查询应该可以解决问题:

SELECT a.seq_id, a_sum + b_sum AS total_sum
FROM   (SELECT   seq_id, amt1 + amt2 AS a_sum
        FROM     table1) a -- no GROUP BY, as seq_id is unique in this table
JOIN   (SELECT   seq_id, SUM(amt3) AS b_sum
        FROM     table2
        GROUP BY seq_id) b ON a.seq_id = b.seq_id

答案 2 :(得分:0)

declare @table1 table (seq_id INT, amt1 decimal(18,2), amt2 decimal(18,2))
declare @table2 table (seq_id INT, code INT, amt3 decimal(18,2))
insert into @table1(seq_id, amt1, amt2)
values
(222 , 0 , 100),
(223 , 0 , 200),
(224 , 300, 0)

insert into @table2(seq_id, code, amt3)
values
(222 , 001 , 100),
(222 , 002 , 150),
(223 , 001 , 100)

select distinct
   t1.seq_id,
   t1.amt1 + t1.amt2 + t2.amt3
from @table1 t1
   join @table2 t2 on t2.seq_id = t1.seq_id

select SUM(t1.amt1) + SUM(t1.amt2) + SUM(t2.amt3)
from @table1 t1
   join @table2 t2 on t2.seq_id = t1.seq_id

答案 3 :(得分:0)

使用JOIN

尝试以下查询
SELECT IFNULL(a.amt1,0) + IFNULL(a.amt2,0) + IFNULL(b.amt3,0) as total_amount 
FROM table1 a JOIN table2 b 
ON a.seq_id=b.seq_id

答案 4 :(得分:0)

我想出了更简单的

SELECT 
(SELECT SUM(atm1) FROM table1)+
(SELECT SUM(amt2) FROM table1)+
(SELECT SUM(amt3) FROM table2)
AS remain

答案 5 :(得分:0)

使用此

select table1.seq_id, sum(table1.amt1 + table1.amt2 + coalesce(table2.amt3)) as total_amount
from table1
  left join table2 on table1.seq_id = table2.seq_id
group by table1.seq_id;