【问题标题】:get the sum of related items that contained in one group the returned on condition获取一组中包含的相关项的总和,返回条件
【发布时间】: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


    【解决方案1】:

    使用另一个窗口函数:

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

    【讨论】:

    • 这很好用,感谢另一种方式使用 cross apply select t.* ,sum(degree) over (partition by name) as [sum] from testTbl t cross apply (select top 3 id from testTbl其中 name = t.name 按年份排序)r where t.id = r.id
    【解决方案2】:

    这可能是一种方法

      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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2013-05-06
      相关资源
      最近更新 更多