insert into table2 (select * from table1)

解决方案 »

  1.   

    declare @sql varchar(2000)
    set @sql='select 物料'
    select @sql=@sql+',[部门'+cast(部门 as varchar)+'数量]=
    isnull(sum(case when 部门='''+cast(部门 as varchar)+''' then 数量 end),0)
    from table1
    group by 部门
    select @sql=@sql+' from table1 group by 物料'
    exec(@sql)
      

  2.   

    declare @tab table(物料 varchar(20),数量 int,部门 varchar(20))
    insert @tab values('001',1,'01')
    insert @tab values('001',4,'02')select 物料,[部门01数量]=sum(case when 部门='01' then 数量 else 0 end),
                [部门02数量]=sum(case when 部门='02' then 数量 else 0 end) from @tab
    group by 物料
      

  3.   

    不用动态的方式,可以这样写!select 物料,[部门01数量]=isnull(sum(case when 部门='01' then 数量 end),0),
    [部门02数量]=isnull(sum(case when 部门='02' then 数量 end),0)
    from table1
    group by 物料
      

  4.   

    select 物料,isnull(sum(case when 部门='01' then 数量 end),0) as 部门01数量,
    isnull(sum(case when 部门='02' then 数量 end),0) as 部门02数量
    from table1
    group by 物料
      

  5.   


    create  table table1(物料 varchar(20),数量 int,部门 varchar(20))
    insert table1 values('001',1,'01')
    insert table1 values('001',4,'02')
    go
    select 物料,
    (select 数量 from table1 where 物料=t.物料 and
    部门='01')as 部门01数量,
    (select 数量 from table1 where 物料=t.物料 and
    部门='02')as 部门02数量
    into #table2
    from table1 t
    group by 物料
    go
    select * from #table2
    drop table #table2