两张桌子的重聚

时间:2011-09-13 07:08:14

标签: sql sql-server tsql sql-server-2008

Create table tbl_test(
    col1 nvarchar(255),
    col2 nvarchar(255),
    sum1 int,
    sum2 int,
    sum3 int)

Create table tbl_test2(
    col1 nvarchar(255),
    col2 nvarchar(255),
    sum1 int,
    sum2 int,
    sum3 int)

Insert into tbl_test (col1, col2, sum1, sum2, sum3)
    select 'a','a',  1 , 1 ,1
        union all
    select 'a','b', 2,2,2
        union all
    select 'a','c', 3,3,3   

Insert into tbl_test2 (col1, col2, sum1, sum2, sum3)
    select 'a','a',  1 , 1 ,1
        union all
    select 'a','b', 2,2,2
        union all
    select 'b','a', 3,3,3   

/ *
我希望我的程序要做的是获取一个新表tbl_result:

tbl_result:
    col1 | col2 | sum1 | sum2 | sum3
     'a'    'a'     2      2     2      || 1 + 1 
     'a'    'b'     4      4     4
     'a'    'c'     3      3     3
     'b'    'a'     3      3     3

* / - 所以我想在两张桌子之间进行某种团聚。

- 到目前为止我找到的方法是:

- 第1步:找到共同的值

Update a 
    set a.sum1 = a.sum1 + b.sum1,
        a.sum2 = a.sum2 + b.sum2,
        a.sum3 = a.sum3 + b.sum3 
from tbl_test a join tbl_test2 b on a.col1 = b.col1 and a.col2 = b.col2

- 第2步:找到新值

Insert into  tbl_test (col1, col2 ,sum1,sum2,sum3)
    select 
            b.col1,
            b.col2,
            b.sum1,
            b.sum2,
            b.sum3
    from tbl_test a right join tbl_test2 b on a.col1 = b.col1 and a.col2 = b.col2
        where a.col1 is null and a.col2 is null

 select * from tbl_test

不幸的是,这还不够好。如果我的表有1.000.000条记录,则连接可能不是最佳解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

FULL JOIN上的两个表格中都需要(col1, col2)和复合索引:

SELECT  COALESCE(a.col1, b.col1)                   AS col1
        COALESCE(a.col2, b.col2)                   AS col2
        COALESCE(a.sum1, 0) + COALESCE(b.sum1, 0)  AS sum1
        COALESCE(a.sum2, 0) + COALESCE(b.sum2, 0)  AS sum2
        COALESCE(a.sum3, 0) + COALESCE(b.sum3, 0)  AS sum3
FROM
    tbl_test a
  FULL JOIN
    tbl_test2 b
      ON  a.col1 = b.col1
      AND a.col2 = b.col2