我有一张这样的桌子:
C1 C2 C3 C4 C5 C6
INTERESES 40530 5 050405011232011 2013 5
PRINCIPAL 40529 5 050405011232011 2016 3
PRINCIPAL 40530 5 050405011232011 2013 4
我需要将这些行按C1,C3和C4分组,并在第2和3泳道的情况下返回最大C5的C2列。我的意思是在这种情况下应该返回:
C1 C2 C3 C4 C5
INTERESES 40530 5 050405011232011 5
PRINCIPAL 40529 5 050405011232011 7
第二行应在C2列中包含40529,因为它在C5列中具有最大值。 C5列应具有上表的C6之和。
我该怎么做?谢谢你,对不起我的英语
答案 0 :(得分:2)
一种方法使用窗口函数来代替聚合:
select c1, c2, c3, c4, sum_c5
from (select t.*,
sum(c5) over (partition by c1, c3, c4) as sum_c5,
row_number() over (partition by c1, c3, c4 order by c5 desc) as seqnum
from t
) t
where seqnum = 1;
Oracle还具有keep
语法,可让您获得聚合中的“第一个”值:
select c1,
max(c2) keep (dense_rank first order by c5 desc) as c2,
c3, c4,
sum(c5)
from t
group by c1, c3, c4;
答案 1 :(得分:0)
您可以使用“不存在”来做到这一点:
select t.c1, t.c2, t.c3, t.c4
from tablename t
where not exists (
select 1 from tablename
where c1 = t.c1 and c2 = t.c2 and c3 = t.c3 and c5 > t.c5
)