7、 请将表 test 
Cus inv Money
北京 苹果 100
北京 李子 200
上海 苹果 400 转变成
Cus 苹果 李子
北京 100 200
上海 400 0

还有一道题目10、 请写SQL语句将下表test 
person ttime Iotype
001 8:00 1
001 12:00 2
001 13:00 1
001 17:00 2
002 8:00 1
002 12:00 2 转换成表
Wpid person in Out
1 001 8:00 12:00
2 001 13:00 17:00
3 002 8:00 12:00 请问如何转换!

解决方案 »

  1.   

    select 
    Cus,
    [苹果]=sum(case when inv='苹果' then [Money] else 0 end),
    [李子]=sum(case when inv='李子' then [Money] else 0 end)
    from 
    Test
    group by Cusgo
      

  2.   

    问题2:用临时表实现
    create table test  (person char(3), ttime nvarchar(5), Iotype int)
    insert test select '001', '8:00', 1 
    insert test select '001', '12:00', 2 
    insert test select '001', '13:00', 1 
    insert test select '001', '17:00', 2 
    insert test select '002', '8:00',1 
    insert test select '002', '12:00', 2 
    go
    select 
    *,row=1,ID=identity(int,1,1)
    into #
    from 
    test t
    order by person asc ,Iotype asc
    go
    update a
    set row=(select count(1) from # where Iotype=a.Iotype and ID!>a.ID)
    from # ago
    declare @s nvarchar(4000)
    set @s=''
    select @s=@s+',['+case when Iotype=1 then 'in' else 'out' end+']=max(case when Iotype='+rtrim(Iotype)+' then ttime else '''' end)'
    from 
    #
    group by Iotype
    exec('select row,person'+@s+' from # group by row,person ')
    row         person in    out   
    ----------- ------ ----- ----- 
    1           001    13:00 12:00
    2           001    8:00  17:00
    3           002    8:00  12:00
      

  3.   


    create table test  (person char(3), ttime nvarchar(5), Iotype int)
    insert test select '001', '8:00', 1 
    insert test select '001', '12:00', 2 
    insert test select '001', '13:00', 1 
    insert test select '001', '17:00', 2 
    insert test select '002', '8:00',1 
    insert test select '002', '12:00', 2 
    go
    select 
    *,row=1,ID=identity(int,1,1)
    into #
    from 
    test t
    --去掉排序
    go
    update a
    set row=(select count(1) from # where Iotype=a.Iotype and ID!>a.ID)
    from # ago
    declare @s nvarchar(4000)
    set @s=''
    select @s=@s+',['+case when Iotype=1 then 'in' else 'out' end+']=max(case when Iotype='+rtrim(Iotype)+' then ttime else '''' end)'
    from 
    #
    group by Iotype
    exec('select row,person'+@s+' from # group by row,person order by row ')/*
    row         person in    out   
    ----------- ------ ----- ----- 
    1           001    8:00  12:00
    2           001    13:00 17:00
    3           002    8:00  12:00
    */
    go
    drop table #,test