1表:A  B  C
1  1  324
2  1  343
3  2   32
1  1  13242表:代码  名称
1     '322'
2     '34'
3     '324'   3表:代码  名称
1      'fsd'
2      'hhh'形成这样的结果:A        B     C
'322'  'fsd'  1648(324+1324)
'34'   'fsd'  343
'324'  'hhh'  32
就是说根据A和B来分组算c的和,再分别用代码名称取代代码。怎么做?

解决方案 »

  1.   

    --tryselect * from
    (
    select A, B, C=sum(C)
    from tb1
    group by A, B
    )tb1
    left join tb2 on tb1.A=tb2.代码
    left join tb3 on tb1.B=tb3.代码
      

  2.   

    create table tb1(A int, B int, C int)
    insert tb1 select 1,  1,  324
    union all select 2,  1,  343
    union all select 3,  2,   32
    union all select 1,  1,  1324create table tb2(代码 int, 名称 varchar(20))
    insert tb2 select  1,     '322'
    union all select 2,     '34'
    union all select 3,     '324'   create table tb3(代码 int, 名称 varchar(20))
    insert tb3 select 1,      'fsd'
    union all select 2,      'hhh'select A=tb2.名称, B=tb3.名称, C=tb1.C
    from
    (
    select A, B, C=sum(C)
    from tb1
    group by A, B
    )tb1
    left join tb2 on tb1.A=tb2.代码
    left join tb3 on tb1.B=tb3.代码--result
    A                    B                    C           
    -------------------- -------------------- ----------- 
    322                  fsd                  1648
    34                   fsd                  343
    324                  hhh                  32(3 row(s) affected)
      

  3.   

    给你最简单的写法
    select 
    select top1 tb2.名称 from tb2 where tb2.代码=t.a),
    select top1 tb3.名称 from tb2 where tb3.代码=t.b),
    t.c from (
    select a,b,sum(c) as c from tb1 group by a,b) t