数据库面试题:求解

cwmwss 2010-07-06 08:15:45
有下列的表数据
姓名 科目 分数
张三 数学 98
张三 语文 90
张三 英语 88
李四 数学 89
李四 语文 94
李四 英语 96
王五 数学 70
王五 语文 60
王五 英语 77

要求写SQL语句得到下面的表
姓名 数学 语文 英语
张三 98 90 88
李四 89 94 96
王五 70 60 77
...全文
124 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
cwmwss 2010-07-07
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 dr_lou 的回复:]
http://www.cnblogs.com/jiajinyi/archive/2009/02/18/1393239.html
[/Quote]额,就知道是网上找的面试题目,数据库接触的少了,这类题目都不会!
要加油了
yangxuebao123 2010-07-06
  • 打赏
  • 举报
回复
动态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 行受影响)
*/


hjjk123 2010-07-06
  • 打赏
  • 举报
回复
慢慢学者写吧/.///
Arthur0088 2010-07-06
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 dr_lou 的回复:]
http://www.cnblogs.com/jiajinyi/archive/2009/02/18/1393239.html
[/Quote]

都可以
cwmwss 2010-07-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 sjc106112 的回复:]
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……
[/Quote]select 科目 from table1 where 姓名=t.姓名 and 科目='数学' 这句是
select 分数 from table1 where 姓名=t.姓名 and 科目='数学' 吧?
还有这里的科目,数学、语文、英语可以不在sql语句里写死吗?由第一个表里查出来
whut_lcy 2010-07-06
  • 打赏
  • 举报
回复
distance->distinct
sjc106112 2010-07-06
  • 打赏
  • 举报
回复
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

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧