当将不同表中的两列相加时,记录总和重复

时间:2016-12-17 06:46:44

标签: sql-server

table 1          table2

   k2   id          k1  id
    3   1           3   1
    3   1           3   1
    3   1           3   1
    5   2           5   2
    6   2           6   2
    7   2           7   2
    7   2           7   2
    7   2           7   2
                    5   2

我需要的输出是:

id   sum k1    sum k1
1       9        9
2       37       32

以下是我使用的查询:

select table1.id,sum(table1.k1),table2.id,sum(table2.k1) from table1,table2
where table1.id= table2.id

但输出我没有权利

3 个答案:

答案 0 :(得分:2)

UNIONGROUP BY的简单组合将为您提供所需的结果。你去.. ..

SELECT id,max(SumK1) AS SumK1,max(SumK2) AS SumK2 FROM
(
    SELECT ID, sum(k1) AS SumK1, NULL AS SumK2 FROM table1 GROUP BY id
    UNION
    SELECT ID, NULL AS SumK1, sum(k2) AS SumK2 FROM table2 GROUP BY id
) T
GROUP BY id 

答案 1 :(得分:1)

这应该可以解决问题:

SELECT 
    COALESCE(table1_result.id1, table2_result.id2) AS id 
  , table1_result.sum_k1 AS sum_k1 
  , table2_result.sum_k2 AS sum_k2 
FROM 
                  ( SELECT id AS id1, SUM(k1) AS sum_k1 FROM table1 GROUP BY id ) AS table1_result 
  FULL OUTER JOIN ( SELECT id AS id2, SUM(k2) AS sum_k2 FROM table2 GROUP BY id ) AS table2_result 
    ON table1_result.id1 = table2_result.id2 

FROM子句中的第一个子查询:

SELECT id AS id1, SUM(k1) AS sum_k1 FROM table1 GROUP BY id 

将为您提供

的结果
id1      sum_k1 
1        9 
2        37 

同样,第二个子查询将给出表2的总和。

id2      sum_k2 
1        9 
2        32 

外部查询匹配来自两个子查询的id值,并将表1和表2中的相应总和彼此并排显示。

id       sum_k1     sum_k2 
1        9          9 
2        37         32 

答案 2 :(得分:0)

我相信table1idk1列。所以,你可以这样做:

select coalesce(t1.id, t2.id) id,
sum(t1.k1) sum_t1_k1,
sum(t2.k1) sum_t2_k1
from table1 t1 full outer join table2 t2
t1.id = t2.id
group by coalesce(t1.id, t2.id);