[英]NTILE only for values different from zero
我有一列有很多零,我只想將非零值放入(大約)相等大小的 N 組中。 所有零值都應該得到組號 0。有沒有一種優雅的方法來做到這一點?
我的第一種方法是使用下面代碼中的ntile_v2
,但是這樣 bin 編號不以 1 開頭,並且我沒有得到 N 個 bin。
with sample_data as
(select
rownum as id,
case when rownum <= 50 then 0 else rownum end as value
from xmltable('1 to 100')
)
select
id,
value,
ntile(50) over (order by value) as ntile_v1,
case when value = 0 then 0 else ntile(50) over (order by value) end as ntile_v2
from sample_data
order by id;
一種解決方案是將非零值放入單獨的 CTE,計算那里的瓦片,然后重新連接:
with sample_data as
(select
rownum as id,
case when rownum <= 50 then 0 else rownum end as value
from xmltable('1 to 100')
)
, sample_data_not_zero as
(select
id,
value,
ntile(50) over (order by value) as ntile_v3
from sample_data
where value <> 0
)
select
sd.id,
sd.value,
nvl(sdnz.ntile_v3, 0) as ntile_v3
from
sample_data sd
left outer join
sample_data_not_zero sdnz on sd.id = sdnz.id
order by id;
不幸的是,我必須為許多不同的列計算這個,我想知道是否有更短的解決方案。
除了當前的案例表達式之外,您還可以根據零與非零對ntile
進行分區:
case
when value = 0 then 0
else ntile(50) over (partition by case when value = 0 then 0 else 1 end order by value)
end as ntile_v3
這似乎與您的union
查詢得到相同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.