日期:2014-05-18  浏览次数:20484 次

这个select语句怎么写啊?
原题是这样的:
编号   姓名   科目   成绩
001   张三     物理   79
001   张三     语文   80
001   张三     数学   85
002   李四     英语   79
002   李四     语文   89
002   李四     电脑   90
要用select语句把它改为以下的样子:
001   张三     物理   79
                    语文   80
                    数学   85
002   李四     英语   79
                    语文   89
                    电脑   90


------解决方案--------------------

create table #t(编号 varchar(100),姓名 varchar(100),科目 varchar(100),成绩 int)

insert into #t
select '001 ', '张三 ', '物理 ',79 union all
select '001 ', '张三 ', '语文 ',80 union all
select '001 ', '张三 ', '数学 ',85 union all
select '002 ', '李四 ', '英语 ',79 union all
select '002 ', '李四 ', '语文 ',89 union all
select '002 ', '李四 ', '电脑 ',90

--增加自动编号列

alter table #t add id int identity(1,1)
go

select
case when id=(select min(id) from #t where 编号=a.编号) then 编号 else ' ' end as 编号,
姓名,
科目,
成绩
from #t as a
order by id

drop table #t
------解决方案--------------------
如果按照表中的次序,可以直接查询:

select case when not exists(select 1 from tablename where 编号=a.编号 and 科目 <a.科目) then a.编号 else null end as 编号,
case when not exists(select 1 from tablename where 编号=a.编号 and 科目 <a.科目) then a.姓名 else null end as 姓名,
科目,成绩
from tablename a
order by a.编号,a.科目

------解决方案--------------------
select case rn when 1 no else ' ' end as no,
case rn when 1 name else ' ' end as name,
subject,score
from
(
select *,(select count(1) from tb where no=t.no and subject <=t.subject) rn
from tb
)t