Oracle SQL SUM MAX

时间:2019-02-11 15:23:51

标签: sql oracle sum max

我有以下情况:

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

Warrens和MIC是主要的校园。因此,当Warrens和MIC的信用时数相同时(如ID 4),则选择Warrens / MIC

  • 对于ID 1:Warrens> MIC,虽然sum(Online)= 6且更大,但还是选择了Warrens
  • 对于ID 2:MIC> Warrens,选择了MIC
  • 对于ID 3:没有主要校园(Warrens / MIC),因此选择了最大学时。 er sum(online)最大,因此选择Online
  • 对于ID 5:West / East / Online都是次要校园,因此选择其中一个。

实际有50多个校园。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果您需要为每个ID选择最长学分,但是如果给定ID的“ MIC”或“ Warrens”存在学分,则所有其他具有相同ID的校区应为忽略,那么最有效的方法是使用FIRST聚合函数,如下所示:

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的最大时数(如果大多数时间都系平局,则为一个校园)。