获取一组中包含的相关项目的总和返回条件

get the sum of related items that contained in one group the returned on condition

这与另一个问题有关 为了说清楚,我将从头开始 这是我的数据库结构 create database testGroupfirst;去

use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl

这是目前的结果

从一个组中获取最新的2个订单等可以通过此代码解决

SELECT name, year, degree, place
FROM 
(SELECT name,degree, year,  place,
    ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
     FROM testTbl   
) t    
WHERE rn in(1,2,3);

--another way
select t.* 
from testTbl t
    cross apply (select top 2 id from testTbl t2 where t2.name = t.name order by degree desc) r
where t.id = r.id

我需要像 sum 这样的聚合函数来获得一组中所有相关项目的总和 我做了这样的代码

select t.*, sum (t.degree) as sumtest 
from testTbl t  
    cross apply (select top 2 id ,degree  , sum (degree) as sumtest from testTbl t2 where t2.place = t.place group by id,degree order by degree  ) r
where t.id = r.id group by t.id,t.name,t.place,t.year,t.degree

但它并没有像我想的那样工作,因为我需要使每个项目本身的聚合值不是标量,我需要获得一组中所有项目的总和 我需要得到的是这张照片中显示的内容

使用另一个window函数:

    SELECT name, year, degree, place, sum(degree) over (partition by name) as [sum]
    FROM 
    (SELECT name,degree, year,  place,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
         FROM #testTbl   
    ) t  
    WHERE rn in(1,2,3);

这可能是一种方法

  select 
  name,
  SUM(degree) sumtest 
  into #test
  from testTbl 
  group by name

  select b.*, a.sumtest from #test a 
  join
  testTbl b on b.name = a.name