读书人

键值对式的表变换数据显示方式说的不

发布时间: 2012-10-10 13:58:11 作者: rapoo

键值对式的表转换数据显示方式,说的不清楚,请进来看
score表
name kemu score
小张 语文 95
小张 数学 95
小李 数学 90
小李 英语 90
小明 语文 85
小明 数学 85
小明 英语 85

现要求查出的数据结构为

name 语文 数学 英语
小张 95 95 null
小李 null 90 90
小明 85 85 85

现SQL语句已经写成
select
name,
case kemu when '语文' then score end as '语文',
case kemu when '数学' then score end as '数学',
case kemu when '英语' then score end as '英语'
from score
但还是达不到要求,请高手帮忙解决!非常感谢

[解决办法]

SQL code
select   name, max(case kemu when '语文' then score end) as '语文', max(case kemu when '数学' then score end) as '数学', max(case kemu when '英语' then score end) as '英语'  from score  group by name
[解决办法]
SQL code
create table #score(name nvarchar(10), kemu nvarchar(10), score int)insert into #scoreselect N'小张', N'语文', 95 union allselect N'小张', N'数学', 95 union allselect N'小李', N'数学', 90 union allselect N'小李', N'英语', 90 union allselect N'小明', N'语文', 85 union allselect N'小明', N'数学', 85 union allselect N'小明', N'英语', 85 --1,子查询法select name,(select MAX(score)from #score where name=s.name and kemu='语文') as 语文,(select MAX(score)from #score where name=s.name and kemu='数学') as 数学,(select MAX(score)from #score where name=s.name and kemu='英语') as 英语 from #score s  group by name    --2,聚合函数+case select   name, max(case kemu when '语文' then score end) as '语文', max(case kemu when '数学' then score end) as '数学', max(case kemu when '英语' then score end) as '英语'  from #score  group by name--3,透视列法select  name,语文,数学,英语 from(select * from #score) as ttpivot(  max(score) for kemu in(语文,数学,英语))as pt 

读书人网 >SQL Server

热点推荐