表的结构
    bh   name  quantity date
    1    电视   100   2008-1-1 0:0:0
    2    冰箱   200   2008-2-1 0:0:0
    3    电视   50    2008-2-25 0:0:0
    4    电视   28    2008-3-12 0:0:0结果要这样的
  name  一月份数量  二月份数量  三月份数  …………
  冰箱   null       200          null
  电视   100        50          28

解决方案 »

  1.   

    bh name quantity date
    1 电视 100 2008-1-1 0:0:0
    2 冰箱 200 2008-2-1 0:0:0
    3 电视 50 2008-2-25 0:0:---select name,sum(case when month(date) = 1 then quantity else 0 end),
    ...
    from ta
    group by name
      

  2.   


    --行转列
    select 
    case when convert(char(6),[date],112) = '200801' then quantity end as ['200801']
    ,case when convert(char(6),[date],112) = '200802' then quantity end as ['200802']
    ...
    ...
    ...
    ...
    ,case when convert(char(6),[date],112) = '200812' then quantity end as ['200812']
    from your_table
      

  3.   

    create table tb(bh int,[name] varchar(10),quantity int,[date] datetime)
    insert into tb select 
    1,'电视',100,'2008-1-1' union all select
    2,'冰箱',200,'2008-2-1' union all select
    3,'电视',50,'2008-2-25' union all select
    4,'电视',28,'2008-3-12' select [name],
    sum(case when month([date])=1 then quantity end) as '一月份',
    sum(case when month([date])=2 then quantity end) as '二月份',
    sum(case when month([date])=3 then quantity end) as '三月份'
    from tb
    group by [name]name       一月份         二月份         三月份         
    ---------- ----------- ----------- ----------- 
    冰箱         NULL        200         NULL
    电视         100         50          28(所影响的行数为 2 行)警告: 聚合或其它 SET 操作消除了空值。drop table tb
      

  4.   


    --创建表test
    if object_id('test') is not null drop table test
    create table test
    (bh int,
     [name] varchar(20),
     quantity int,
    [date] datetime
    )
    --插入数据
    insert into test
    select 1,'电视','100','2008-1-1 0:0:0' union all
    select 2,'冰箱','200','2008-2-1 0:0:0' union all
    select 3,'电视','50','2008-2-25 0:0:0' union all
    select 4,'电视','28','2008-3-12 0:0:0'--进行查询
    declare @sqlstr varchar(8000)
    select  @sqlstr = ''
    select  @sqlstr = @sqlstr +',sum(case [date] when '''+ltrim([date])+''' then quantity else null end) as '+'第'+ltrim([date])+'月份数量'
    from (select [name],[quantity],month([date]) as [date] from test)a 
    group by  [date]
    exec('select [name]'+@sqlstr+' from (select [name],[quantity],month([date]) as [date] from test)a group by [name]')--查询结果
    /*
    name 第1月份数量 第2月份数量 第3月份数 …………
    冰箱 NULL 200 NULL
    电视 100 50 28
    */