Create table test (name char(10),km char(10),cj int)
go
insert test values('张三','语文',80)
insert test values('张三','数学',86)
insert test values('张三','英语',75)
insert test values('李四','语文',78)
insert test values('李四','数学',85)
insert test values('李四','英语',78)想变成姓名   语文   数学   英语
张三   80     86     75
李四   78     85     78
declare @sql varchar(8000)
set @sql = 'select name'
select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
 from (select distinct km from test) as a
select @sql = @sql+' from test group by name'
exec(@sql)drop table test
drop table table1 
go

解决方案 »

  1.   

    select 日期,入库数量1,入库地点1 from 表1
    union all
    select 日期,入库数量2,入库地点2 from 表1
    union all
    select 日期,出库数量1,出库地点1 from 表1
    union all
    select 日期,出库数量2,出库地点2 from 表1
    order by a.日期
      

  2.   

    insert 结果集
    select 日期, 入库数量1, 入库地点1 from 表1
    union all
    select 日期, 入库数量2, 入库地点2 from 表1
    union all
    select 日期, 出库数量1, 出库地点1 from 表1
    union all
    select 日期, 出库数量2, 出库地点2 from 表1