我需要以忽略空值的方式分配排名。
select root_cause_desc,
case
when root_cause_desc is null
then null
else rank() over ( order by excess_value desc)
end gap_rank
from table.
where root_cause_desc is not null
给予
ROOT_CAUSE_DESC EXCESS_VALUE TOTAL_EXCESS_VALUE_WK GAP_RANK
advanced shipment 120.9750138 -760356.4054 10
dfdfdfdf222 0 -1696000.946 11
Root Cause -0.0760554 -760356.4054 12
test one more -656.277192 -760356.4054 13
earlier truck -77099.35 720093.3712 14
它忽略 null
值并为其分配等级,即使对于 null
根本原因也是如此。我希望 gap_rank 为 1,2,3,4。现在请告诉我该怎么做。
最佳答案
问题在于 RANK()
独立于您的 case 语句;它通过您提供的 ORDER BY 子句对整个查询进行排序。
使用 NULLS LAST 关键字将 NULL 值放在订单的末尾,然后您的 CASE 语句将起作用。例如:
with the_data as (
select level as a
, nullif(nullif(level, 5), 8) as b
from dual
connect by level <= 10
)
select a
, b
, case when b is null then null
else rank() over ( order by case when b is not null then 1
end nulls last
, a )
end as "rank"
from the_data
order by a;
A B rank
---------- ---------- ----------
1 1 1
2 2 2
3 3 3
4 4 4
5
6 6 5
7 7 6
8
9 9 7
10 10 8
10 rows selected.
关于sql - 如何在oracle中为非空值分配等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18307716/