的Oracle SQL SUM MAX

问题描述 投票:0回答:2

我有以下情形:

ID    Campus    Credit_Hr
===== ======      ====           
1      MIC          3                
1      Warrens      4            
1      Online       3             
1      Online       3  
2      MIC          5
2      Warrens      3
2      Online       6
3      Online       3
3      Online       3
3      West         2
4      Warrens      3
4      MIC          3
4      West         7
5      Online       3
5      West         3
5      East         3

沃伦斯和MIC是各大校园。所以,当沃伦和MIC具有等于信用小时,像ID 4,选择了任一沃伦/ MIC

  • 对于ID 1:沃伦> MIC,选择沃伦虽然总和(在线)= 6和更大
  • 对于ID 2:MIC>沃伦,选择了MIC
  • 对于ID 3:无重大校区(沃伦/ MIC),所以选择了最大的信用小时。呃总和(在线)为最大值,从而选择在线
  • 对于ID 5:西/东/网上都是次要的校园里,所以选了其中任何一个。

实际可超过50个校区。

sql oracle sum max
2个回答
1
投票

分配重大的校园信息,然后用此列排序,除了小时的总和:

dbfiddle demo

select * 
  from (
    select a.*, row_number() over (partition by id order by major, sm desc) rn
      from (
        select id, campus, 
               case when campus in ('MIC', 'Warrens') then 1 else 2 end major, 
               sum(credit_hr) over (partition by id, campus) sm
          from t) a)
  where rn = 1

0
投票

如果你需要的是选择最高学分为每个ID,但在这样一种方式,如果“MIC”或“养兔场”存在一个给定的ID学分,那么所有其他校园为同一ID应该被忽略,那么最有效的方法是使用第一个聚合函数,就像这样:

with
  sample_data(id, campus, credit_hr) as (
    select 1, 'MIC'    , 3 from dual union all
    select 1, 'Warrens', 4 from dual union all
    select 1, 'Online' , 3 from dual union all
    select 1, 'Online' , 3 from dual union all
    select 2, 'MIC'    , 5 from dual union all
    select 2, 'Warrens', 3 from dual union all
    select 2, 'Online' , 6 from dual union all
    select 3, 'Online' , 3 from dual union all
    select 3, 'Online' , 3 from dual union all
    select 3, 'West'   , 2 from dual union all
    select 4, 'Warrens', 3 from dual union all
    select 4, 'MIC'    , 3 from dual union all
    select 4, 'West'   , 7 from dual union all
    select 5, 'Online' , 3 from dual union all
    select 5, 'West'   , 3 from dual union all
    select 5, 'East'   , 3 from dual
)
select   id, 
         max(credit_hr) keep (dense_rank first 
             order by case when campus in ('MIC', 'Warrens') then 0 end)
         as max_hr
from     sample_data
group by id
order by id
;

   ID             MAX_HR
----- ------------------
    1                  4
    2                  5
    3                  3
    4                  3
    5                  3

您也可以修改查询(添加更多的列)显示最大无论是从主校区(即,如果该ID过任何学分从各大校园之一),和/或显示其校园有最大该ID小时(或校园中的一个,如果有对大多数小时并列)。

© www.soinside.com 2019 - 2024. All rights reserved.