一道合并成绩最高科目的解决方法(2)

来源:未知 责任编辑:责任编辑 发表时间:2014-01-20 07:54 点击:
        union all  
        SELECT     姓名, 英语 as 成绩,'英语' 科目  
        FROM         ChengJi ) T  
        group by 姓名,科目) B ON A.姓名=B.姓名 and A.成绩=B.成绩  
-------------------------------------------------------------  
select 姓名,成绩,dbo.Getkemu(姓名) as 科目 from ChengJi2   
group by 姓名, 成绩  -www.2cto.com-

网友一的方案:
[sql]
select * into #tb  
from(  
select '张三' as name,60 as 语文,70 as 数学,80 as 英语  
union  
select '李四' as name,90 as 语文,70 as 数学,90 as 英语  
union  
select '王武' as name,80 as 语文,80 as 数学,80 as 英语  
) a  
----------------  
select name,max(成绩) as 成绩,  
 (select case when 语文=MAX(成绩) then '语文,' else '' end+  
         case when 数学=MAX(成绩) then '数学,' else '' end+  
         case when 英语=MAX(成绩) then '英语' else '' end  
 from #tb ab where ab.name=a.name) as 科目  
from  
(  
select name,语文 as 成绩,'语文' 科目  
from #tb  
union all  
select name,数学 as 成绩,'数学' 科目  
from #tb  
union all  
select name,英语 as 成绩,'英语' 科目  
from #tb  
) a group by a.name  
--------------------  
drop table #tb  
网友二的方案:
[sql]
create table #tmp  
(  
id int primary key,  
[name] varchar(255),  
语文 int,  
数学 int,  
英语 int  
)  
;  
insert into #tmp values(1, '张三', 75, 90, 85);  
insert into #tmp values(2, '李四', 80, 85, 85);  
  
with  
tree as  
(  
select [name], 分数, 科目  from #tmp  
unpivot  
(  
分数 for 科目 in (语文, 数学, 英语)  
)  
as unpvt  
),  
maxTree as  
(  
select * from tree t1 where 分数 >= (select max(分数) from tree t2 where t1.name = t2.name)  
)  
select name, 分数, 科目 = stuff((select ',' + 科目 from maxTree t1 where t1.name = t2.name for xml path('')), 1, 1, '')  
from maxTree t2  
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • sql常见面试题
  • SQL SERVER 2005性能之跟踪
  • SQL编程(一)
  • LINUX上RMAN自动备份脚本
  • sql server面试题
  • 浅谈SQL Server中的事务日志(三)----在简单恢复模式下日志的角色
  • SQL小技巧系列 --- 行转列合并
  • 如何将多个SQL查询统计结果一次显示出来
  • sql server 列转行
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1