日期:2014-05-17  浏览次数:20498 次

键值对式的表转换数据显示方式,说的不清楚,请进来看
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 
但还是达不到要求,请高手帮忙解决!非常感谢
------解决方案--------------------
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

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



create table #score
(
name nvarchar(10),
 kemu nvarchar(10),
 score int
)

insert into #score
select N'小张', N'语文', 95 union all
select N'小张', N'数学', 95 union all
select N'小李', N'数学', 90 union all
select N'小李', N'英语', 90 union all
select N'小明', N'语文', 85 union all
select N'小明', N'数学', 85 union all
select 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 tt
pivot
(
  max(score) for kemu in(语文,