日期:2014-05-19  浏览次数:20569 次

一个SQL查询语句求教
名     分数
A             7
B             3
A             2
C             5
A             4
C             2
B             7
C             6
这样的一个表。,我想算每个人分数最高的两个分的和,应该怎么做呢?


------解决方案--------------------
我想算每个人分数最高的两个分的和
---------
是這個意思嗎
------解决方案--------------------
select f_num2,sum(point) from(
select name,max(point) as point from a group by name
union all
select name, max(point) as point from a where point not in (select max(point) from a group by name ) group by name ) a group by name
------解决方案--------------------
好象是這樣

--如果相同名的分數不會重復
Select 名, SUM(分数) As 分数 From 表 A
Where 分数 In (Select TOP 2 分数 From 表 Where 名 = A.名) Group By 名
------解决方案--------------------
举例如下:
create table a(名 varchar(20),分数 int)
insert a values( 'A ',7)
insert a values( 'B ',3)
insert a values( 'A ',2)
insert a values( 'C ',5)
insert a values( 'A ',4)
insert a values( 'C ',2)
insert a values( 'B ',7)
insert a values( 'C ',6)
go
select 名,sum(分数) 分数
from a b
where (select count(*) from a where 名=b.名 and 分数> =b.分数) <=2
group by 名
order by 名,分数 desc
go
返回:
名 分数
-------------------- -----------
A 11
B 10
C 11

(所影响的行数为 3 行)
------解决方案--------------------
create table # (
name varchar(10),
score int)

insert #


select 'A ', 7
union all
select 'B ', 3
union all
select 'A ', 2
union all
select 'C ', 5
union all
select 'A ', 4
union all
select 'C ', 2
union all
select 'B ', 7
union all
select 'C ', 6
union all
select 'B ',6
union all
select 'A ',1
union all
select 'B ',1
union all
select 'C ',1
union all
select 'A ',7

select name,sum(score) from #
where (select count(*) from # t where t.name = #.name and t.score > = #.score) <= 2
group by name

drop table #
----------------------------
结果
A 14
B 13
C 11
----------------------------
原来
A 7
B 3
A 2
C 5
A 4
C 2
B 7
C 6
B 6
A 1
B 1
C 1
A 7