有数据表tab1,字段name
数据:
name
a
b
c
另有数据表tab2,字段name,val
name   val
a      1
b      2
d      3
e      4
需要得到结果:tab1和tab2通过name关联
name val
a    1
b    2
c    0
oth  7
规则:通过tab1匹配tab2,如包含则取值,如不包含则添加oth,把所有未匹配值累加
(如,oth=d+e)
请问如何写sql?谢谢1

解决方案 »

  1.   

    declare @ta table(name varchar(2))
    insert @ta select 'a'
    union all select 'b'
    union all select 'c'declare @tb table(name varchar(2),val int)
    insert @tb select 'a',1
    union all select 'b',2
    union all select 'd',3
    union all select 'e',4select [name]=isnull(a.name,'oth'),
    val=sum(isnull(b.val,0))
    from @ta a full join @tb b on a.name=b.name
    group by isnull(a.name,'oth')
    (3 行受影响)(4 行受影响)
    name val
    ---- -----------
    a    1
    b    2
    c    0
    ot   7(4 行受影响)
      

  2.   

    select name=isnull(a.name,'oth'),val=isnull(sum(b.val),0) from @ta a full join @tb b
    on a.name=b.name
    group by a.name