有下列的表数据
姓名    科目      分数
张三    数学      98
张三    语文      90
张三    英语      88
李四    数学      89
李四    语文      94
李四    英语      96
王五    数学      70
王五    语文      60
王五    英语      77要求写SQL语句得到下面的表
姓名   数学   语文   英语
张三   98     90     88
李四   89     94     96
王五   70     60     77

解决方案 »

  1.   

    select distance 姓名,(select 科目 from table1 where 姓名=t.姓名 and 科目='数学') as 数学,(select 科目 from table1 where 姓名=t.姓名 and 科目='语文') as 语文,(select 科目 from table1 where 姓名=t.姓名 and 科目='英语') as 英语 from table1 t 
      

  2.   

    select 科目 from table1 where 姓名=t.姓名 and 科目='数学' 这句是
    select 分数 from table1 where 姓名=t.姓名 and 科目='数学' 吧?
    还有这里的科目,数学、语文、英语可以不在sql语句里写死吗?由第一个表里查出来
      

  3.   

    http://www.cnblogs.com/jiajinyi/archive/2009/02/18/1393239.html
      

  4.   

    动态sql,行转成列。
    --1、行互列 
    if not object_id('Class') is null
        drop table Class
    Go
    Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
    Insert Class
    select N'张三',N'语文',78 union all
    select N'张三',N'数学',87 union all
    select N'张三',N'英语',82 union all
    select N'张三',N'物理',90 union all
    select N'李四',N'语文',65 union all
    select N'李四',N'数学',77 union all
    select N'李四',N'英语',65 union all
    select N'李四',N'物理',85 
    Go
    --2000方法:
    动态:declare @s nvarchar(4000)
    set @s=''
    Select     @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
    from Class group by[Course]
    exec('select [Student]'+@s+' from Class group by [Student]')
    生成静态:select 
        [Student],
        [数学]=max(case when [Course]='数学' then [Score] else 0 end),
        [物理]=max(case when [Course]='物理' then [Score] else 0 end),
        [英语]=max(case when [Course]='英语' then [Score] else 0 end),
        [语文]=max(case when [Course]='语文' then [Score] else 0 end) 
    from 
        Class 
    group by [Student]GO
    动态:declare @s nvarchar(4000)
    Select     @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
    exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')生成静态:
    select * 
    from 
        Class 
    pivot 
        (max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b生成格式:
    /*
    Student 数学          物理          英语          语文
    ------- ----------- ----------- ----------- -----------
    李四      77          85          65          65
    张三      87          90          82          78(2 行受影响)
    */