数据如下: date            code    data  type 2009-10-01      1      100  类别1 2009-10-01      2      200  类别2 2009-10-01      3      300  类别3 2009-10-02      1      400  类别1 2009-10-02      2      500  类别2 怎样写sum和group by统计每个类别的总数,得到下面的结果? type  data 
  
类别1  500 类别2  700 类别3  300 

解决方案 »

  1.   

    SELECT TYPE,SUM(DATA) FROM TB GROUP BY TYPE
      

  2.   

    select type,sum(data) as data
    from tb
    group by type
      

  3.   

    select type,sum(isnull(data,0)) as data
    from tb
    group by type
      

  4.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([date] datetime,[code] int,[data] int,[type] varchar(5))
    insert [tb]
    select '2009-10-01',1,100,'类别1' union all
    select '2009-10-01',2,200,'类别2' union all
    select '2009-10-01',3,300,'类别3' union all
    select '2009-10-02',1,400,'类别1' union all
    select '2009-10-02',2,500,'类别2'
     
    ---查询---
    select type,sum(data) as data
    from tb
    group by type---结果---
    type  data        
    ----- ----------- 
    类别1   500
    类别2   700
    类别3   300(所影响的行数为 3 行)
      

  5.   

    select
     [type],
     sum(data) as data
    from
     tb
    group by
     [type]
      

  6.   

    select type,sum(date) as date from table
    group by type
      

  7.   

    select type,sum(data) from tb group by type