我有以下情形:
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
实际可超过50个校区。
分配重大的校园信息,然后用此列排序,除了小时的总和:
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
如果你需要的是选择最高学分为每个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小时(或校园中的一个,如果有对大多数小时并列)。