如何从另一个表获取数据总和

时间:2019-07-18 13:57:34

标签: sql sql-server

示例

共有三个表:A_TBLB_TBLC_TBL

CREATE TABLE A_tbl (    
    NUM int
)
insert into a_tbl values('1000');

CREATE TABLE B_tbl (    
    NUM int 
) 
insert into B_tbl values('2000')

CREATE TABLE C_tbl (    
    NUM int
) 

A_TBL

NUM
1000

B_TBL

NUM
2000

我想将表A和表B的总和放在表C中。

所需的输出

C_TBL

NUM
3000

3 个答案:

答案 0 :(得分:0)

您需要UNION ALL

INSERT INTO c_tbl(num)
  SELECT SUM(num) 
  FROM (SELECT a.NUM FROM a_tbl a UNION ALL
        SELECT b.NUM FROM b_tbl b
       ) ab; 

答案 1 :(得分:0)

INSERT INTO C_tbl(NUM)
SELECT SUM(NUM) AS NUM
FROM (
         SELECT NUM
         FROM A_tbl
         UNION ALL
         SELECT NUM
         FROM B_tbl
     ) sub;

答案 2 :(得分:0)

您可以在select中使用子查询:

insert into c (num)
    select ( (select sum(num) from a) + select sum(num) from b) )