【发布时间】:2017-11-15 14:38:15
【问题描述】:
这与另一个问题有关get first record in group by result base on condition 说清楚,我将从头开始 这是我的数据库结构创建数据库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
但它并没有像我想的那样工作,因为我需要为每个项目本身设置聚合值而不是标量,我需要获取一组中所有项目的总和 我需要得到的是这张照片中显示的
【问题讨论】:
标签: sql-server group-by sql-order-by aggregate-functions database-partitioning