一:合并相同数据;
有如下表
tb_Test
c_MobileNo   c_Acct    i_Money
13312345678  1         50.00
13312345678  1         20.00
13388888888  2         60.00如果c_MobileNo和c_Acct相同的,i_Money则相加得到如下结果:
c_MobileNo   c_Acct    i_Money
13312345678  1         70.00
13388888888  2         60.00
二:
列变行;
有如下表
tb_Test
c_MobileNo   c_Acct   i_Money
13312345678  1        70.00
13312345678  2        50.00
13388888888  2        60.00
13388888888  3        20.00c_MobileNo相同的列变行,得到如下结果:c_MobileNo   1      2      3
13312345678  70.00  50.00
13388888888         60.00  20.00空白的为空值!

解决方案 »

  1.   

    第一题:select c_MobileNo,c_Acct,sum(i_Money) as i_Money from tb_Test
    group by c_MobileNo,c_Acct
      

  2.   

    declare @sql varchar(8000)
    set @sql = 'select c_MobileNo'
    select @sql = @sql + ',sum(case c_Acct when '''+c_Acct+''' then i_Money end) ['+c_Acct+']'
     from (select distinct c_Acct from tb_Test) as aselect @sql = @sql+' from tb_Test group by c_MobileNo' 
    exec(@sql)
      

  3.   

    一.
    select c_mobileno,c_Acct,i_Money=sum(i_Money) from tb_Test
    group by c_mobileno二.
    select c_mobileno,
    '1'=sum(case when c_acct=1 then isnull(i_money,0) end), 
    '2'=sum(case when c_acct=2 then isnull(i_money,0) end), 
    '3'=sum(case when c_acct=3 then isnull(i_money,0) end)
    from tb_test
    group by c_mobileno
      

  4.   


    一.
    select c_mobileno,c_Acct,i_Money=sum(i_Money) from tb_Test
    group by c_mobileno,c_acct
      

  5.   

    create table tb(c_MobileNo varchar(20),c_Acct int,i_Money dec(6,2))
    insert tb select '13312345678' , 1     ,    50.00
    union all select '13312345678'  ,1     ,    20.00
    union all select '13388888888'  ,2    ,     60.00
    --1
    select c_MobileNo,c_Acct,sum(i_Money) as i_Money from tb group by c_MobileNo,c_Acctdrop table tb
    --2
    create table tb(c_MobileNo varchar(20),c_Acct int,i_Money dec(6,2))
    insert tb select '13312345678' , 1       , 70.00
    union all select '13312345678' , 2        ,50.00
    union all select '13388888888'  ,2        ,60.00
    union all select '13388888888' , 3       , 20.00declare @sql varchar(8000)
    set @sql='select c_MobileNo'
    select @sql=@sql+',['+cast([c_Acct] as varchar)+']=sum(case c_Acct when '+cast(c_Acct as varchar)+' then i_Money else NULL end)' from tb group by c_Acct
    exec(@sql+' from tb group by c_MobileNo')drop table tb