有一个表test_1(姓名,课目,分数) 数据如下: 
cd 语文 80
cd 数学 81
cd 外语 82
cd 化学 84
bd 语文 80
bd 数学 81
bd 外语 82
如何用sql语句查询出结果如下:
姓名,语文,数字,外语,化学
cd  80   81  82  84
bd  80   81  82  0
                                     

解决方案 »

  1.   

    create table #t(
    姓名 varchar(10),
    科目 varchar(50),
    分数 int
    )insert #t select 'cd','语文',80
    union all select 'cd','数学',81
    union all select 'cd','外语',82
    union all select 'cd','化学',84
    union all select 'bd','语文',80
    union all select 'bd','数学',81
    union all select 'bd','外语',82declare @sql varchar(8000)
    set @sql=N'select 姓名'
    select @sql=@sql+',sum(case 科目 when '''+科目+''' then 分数 else 0 end) as ['+科目+']'
    from (select distinct 科目 from #t) aselect @sql=@sql+' from #t group by 姓名'
    print @sql
    exec (@sql)
    drop table #t
      

  2.   

    LS的写的是SQL SERVER的写法。希望写出MYSQL的。
      

  3.   

    一楼的兄弟,借你的数据用一下:set names gbk;
    create table lk2(
    username varchar(64),
    `subject` varchar(20),
    score int
    ) engine=myisam charset=gbk;不过这个UNION ALL 语法MYSQL 能用。insert into lk2
    select 'cd','语文',80
    union all select 'cd','数学',81
    union all select 'cd','外语',82
    union all select 'cd','化学',84
    union all select 'bd','语文',80
    union all select 'bd','数学',81
    union all select 'bd','外语',82;set names gbk;select username,sum(yuwen),sum(shuxue),sum(waiyu),sum(huaxue) from 
    (select username,
    (case subject when '语文' then score else 0 end) 'yuwen', 
    (case subject when '数学' then score else 0 end) 'shuxue', 
    (case subject when '外语' then score else 0 end) 'waiyu', 
    (case subject when '化学' then score else 0 end) 'huaxue'
    from lk2) T group by username order by username desc;结果:query result(2 records)
    username sum(yuwen) sum(shuxue) sum(waiyu) sum(huaxue) 
    cd 80 81 82 84 
    bd 80 81 82 0