我目前正在尝试根据自定义条件对结果进行排名。让我们假设我的数据如下所示:
col1 col2 col3
-----------------------
1 1 2
1 3 33
2 4 5
3 6 40
1 2 5
3 5 10
Run Code Online (Sandbox Code Playgroud)
我现在想按 col1 分组并按 col2 排序,然后对结果进行排名。但是,我只想在 col3 大于 30 时提高排名。因此结果应如下所示:
col1 col2 col3 rank
-----------------------------
1 1 2 1
1 2 5 1
1 3 33 2
2 4 5 1
3 5 10 1
3 6 40 2
Run Code Online (Sandbox Code Playgroud)
我只是找不到解决问题的优雅方法。如果我只使用经典排名,那么整个事情当然行不通;例如:
RANK() OVER (PARTITION BY col1 ORDER BY col2)
如果可能的话,由于性能问题,我想在这里使用窗口函数。我也在 Google 的 Bigquery 环境中工作。
像这样的东西似乎有效。我没有执行 a ,而是计算值大于 30 的rank行数的累积和。col3
with x as (
select 1 col1, 1 col2, 2 col3 from dual union all
select 1, 3, 33 from dual union all
select 2, 4, 5 from dual union all
select 3, 6, 40 from dual union all
select 1, 2, 5 from dual union all
select 3, 5, 10 from dual
)
select col1, col2, col3,
sum( case when col3 > 30 then 1 else 0 end )
over( partition by col1
order by col2 ) + 1 rnk
from x
Run Code Online (Sandbox Code Playgroud)
用于此目的的 sqlfiddle也可用。
| 归档时间: |
|
| 查看次数: |
4590 次 |
| 最近记录: |