1

이것은 다른 질문과 관련되어 있습니다. get first record in group by result base on condition 처음부터 시작하겠습니다. 이것은 데이터베이스 구조를 만드는 데이터베이스입니다. testGroupfirst; 이 지금 enter image description here하나의 그룹에 포함 된 관련 항목의 합계를 반환합니다.

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 

내가 얻을 필요가이 코드에 의해 해결 될 수 이것에 의해 그룹에서 등 최신이 개 주문을 얻을 때까지 결과입니다

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 

이동 합계와 같은 함수로 하나의 그룹에있는 모든 관련 항목의 합계를 얻습니다. 이 코드는 다음과 같습니다.

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 

하지만 모든 항목 자체에 대해 스칼라가 아닌 집계 값을 만들어야 할 필요가 있다고 생각한 것처럼 작동하지 않았습니다. 하나의 그룹에있는 모든 항목의 합계를 가져와야합니다. 이 사진에 표시된 내용이 무엇인지 알 수 있습니다. enter image description here

답변

3

를 사용하여 다른 창 기능 :

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); 
+1

, 감사다른 방법은 십자가를 사용하여 적용합니다. testTbl에서 으로 합계 (도) 이상을 (이름으로 파티션) 선택합니다. 십자가 적용 (testTbl에서 상위 3 개 ID를 선택하십시오. 여기서 name = t.name은 연도 순으로 선택) r 여기서 t.id = r.id – user4833581

1

이 될 수있는 하나 개의 방법이 잘 작동됩니다

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 
관련 문제