一道合并成绩最高科目的解决方法(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
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>