我有一个表,其中包含细分,part_name,营业额,例如:
segment part_name cust_id turnover
A blue 1 4202
A red 1 625342
A blue 9 369
B orange 6 31323
B orange 8 4678
B red 8 27847
C red 3 13001
C blue 4 3097
C blue 5 423
C blue 2 9753
我尝试了很多无效的内部联接,并在互联网上搜寻了一段时间之后,决定转向SO
实际结果只能是3行(每段一个),其part_name具有最大营业额的总和(营业额需要由part_name相加,然后需要将营业额最大的零件名称与返回-并非仅是一行中的最大营业额,而是营业额的总和(按part_name)
A red 625342
B orange 36001
C blue 13273
谢谢。
答案 0 :(得分:2)
您想要row_number()
:
select t.*
from (select t.*, row_number() over (partition by segment order by turnover desc) as seq
from table t
) t
where seq = 1;
如果您与turnover
有联系,请改用dense_rank()
。
编辑:我误读了您想要使用row_number()
的窗口功能的问题
select t.segment, t.part_name, t.t_turnover as turnover
from (select t.*, row_number() over (partition by segment order by t_turnover desc) as seq
from (select t.*, sum(turnover) over (partition by segment, part_name) as t_turnover
from table t
) t
) t
where seq = 1;