日期:2014-05-20  浏览次数:20699 次

帮忙写个SQL语句(在线等)
表结构
姓名 学科 成绩
张三 语文 85
张三 数学 95
张三 英语 90
李四 语文 85
李四 数学 95
李四 英语 90 
王五 语文 85
王五 数学 95
王五 英语 90

写出此查询结果得sql语句
姓名 语文 数学 英语
张三 85 95 90
李四 85 95 90
王五 85 95 90

------解决方案--------------------
select distinct a.name ,a.xueke as 语文,b.xueke as 数学,c.xueke as 英语 From Student a,Student b,Student c Where a.name=b.name and a.name=c.name and a.xueke='语文' and b.xueke='数学' and c.xueke='英语'
------解决方案--------------------
3楼的写的差不多了,只是一个地方写错了,我修改了下,可以得到你要的结果:
select distinct a.name ,a.grade as 语文,b.grade as 数学,c.grade as 英语 
From dbo a,dbo b,dbo c 
Where a.name=b.name and a.name=c.name 
and a.study='语文' and b.study='数学' and c.study='英语'
------解决方案--------------------
--表结构
create table test
(
id int identity(1,1) primary key,
name varchar(50),
jub varchar(50),
score int
)
go
--测试数据
insert into test values('张三','语文',85)
insert into test values('张三','数学',95)
insert into test values('张三','英语',90)

insert into test values('李四','语文',85)
insert into test values('李四','数学',90)
insert into test values('李四','英语',95)

insert into test values('王五','语文',85)
insert into test values('王五','数学',95)
insert into test values('王五','英语',90)

--要求的结果SQL语句
select name '姓名',jub '学科',score '成绩' from test

select name,
sum(case when jub = '语文' then score else 0 end) 语文,
sum(case when jub = '数学' then score else 0 end) 数学,
sum(case when jub = '英语' then score else 0 end) 英语
from test
group by name