我有以下三个字段:A,B,C
A         B       
北京      5      
上海      3      
上海      3      
北京      1      
北京      1      
上海      2      
天津      5      
天津      3      我想用一句sql语句得到它们的合计:北京    7
上海    8
天津    8

解决方案 »

  1.   

    select A,sum(B) as [SumB] 
    from tablename
    group by A
      

  2.   

    select a,sum(b) as b from TableName group by a
      

  3.   

    提示:
    服务器: 消息 409,级别 16,状态 2,行 4
    sum or average aggregate 运算不能以 varchar 数据类型作为参数。
    我的 B数据类型是字符串。
      

  4.   

    create table test(A varchar(10),B varchar(10))
    insert test
    select '北京','5' union all        
    select '上海','3' union all        
    select '上海','3' union all        
    select '北京','1' union all        
    select '北京','1' union all        
    select '上海','2' union all      
    select '天津','5'     
    --select * from testselect A,sum(cast(B as int)) as SumB from test group by Adrop table test
      

  5.   

    select A,sum(B) as [SumB]
    from tablename
    group by A
    如果是字符型的转换一下.