Sql按每个组的总和分组
我有一张这样的桌子:Sql按每个组的总和分组,sql,oracle,Sql,Oracle,我有一张这样的桌子: 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车道的情况下,
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的总和
我该怎么做?感谢并抱歉我的英语一种方法使用窗口函数,而不是聚合:
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
语法,允许您在聚合中获取“first”值:
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;
一种方法不使用聚合,而是使用窗口函数:
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
语法,允许您在聚合中获取“first”值:
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;
您可以在不存在的情况下执行此操作:
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
)
您可以在不存在的情况下执行此操作:
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
)
它工作,但我有一个小问题,我需要求和列了。我在op中解释。如果我把这个加起来,你能帮我吗?它只适用于一个row@AbelJuanRodr伊格斯。使用第二个版本的
sum(c5)
。它可以工作,但我有一个小问题,我也需要对一列求和。我在op中解释。如果我把这个加起来,你能帮我吗?它只适用于一个row@AbelJuanRodr伊格斯。将第二个版本与sum(c5)
一起使用。