http://expert.csdn.net/Expert/topic/2102/2102788.xml?temp=.1526911

解决方案 »

  1.   

    declare @sql varchar(8000)
    set @sql = 'select day(日期) 号数'
    select @sql = @sql + ',sum(case 名称 when '''+名称+''' then 库存 else 0 end) ['+名称+'库存],sum(case 名称 when '''+名称+''' then 销售数量 else 0 end) ['+名称+'销售数量]'
      from (select distinct 名称 from 表A) as a
    select @sql = @sql+' from 表A group by day(日期)'exec(@sql)
    go
      

  2.   

    declare @sql varchar(8000)
    set @sql = 'select day(日期) 号数'
    select @sql = @sql + ',sum(case 名称 when '''+名称+''' then 库存 else 0 end) ['+名称+'库存],sum(case 名称 when '''+名称+''' then 销售数量 else 0 end) ['+名称+'销售数量]'
      from (select distinct 名称 from 表A) as a
    select @sql = @sql+' from 表A group by day(日期)'exec(@sql)
    go
      

  3.   

    交叉表+动态生成SQL的
    declare @sql varchar(8000)
    set @sql='select day(日期) as 号数'
    select @sql=@sql
        +char(13)+',sum(case 名称 when '''+名称+''' then 库存 end) as ['+名称+'_库存]'
        +char(13)+',sum(case 名称 when '''+名称+''' then 销售数量 end) as ['+名称+'_销售数量]'
    from(select distinct 名称 from 表A) as a
    set @sql=@sql+char(13)+' from 表A group by day(日期)'exec(@sql)
      

  4.   

    create table 表A
    (
    日期  datetime, 
    名称  char(10),
    库存  float,
    销售数量 float
    )
    insert 表A values('2003-08-01','w1',100,10)
    insert 表A values('2003-08-01','w2',10,2)
    insert 表A values('2003-08-02','w1',90,2)
    insert 表A values('2003-08-02','w2',8,6)go
    declare @sql varchar(8000)
    set @sql = 'select day(日期) 号数'
    select @sql = @sql + ',sum(case 名称 when '''+名称+''' then 库存 else 0 end) ['+名称+'库存],sum(case 名称 when '''+名称+''' then 销售数量 else 0 end) ['+名称+'销售数量]'
      from (select distinct 名称 from 表A) as a
    select @sql = @sql+' from 表A group by day(日期)'exec(@sql)
    go肯定可以了,测试通过。