我有这样的数据
---------------------------
| code | other column
---------------------------
| C | a
| null | a
| A | a
| null | a
| null | a
----------------------------
如何编写查询以获取row_number而不计算空列。
----------------------------------
| id | code | other column |
----------------------------------
| 1 | C | a
| | null | a
| 2 | A | a
| | null | a
| | null | a
----------------------------------
答案 0 :(得分:5)
嗯,不是特别的。但是你可以通过使用条件逻辑得到你想要的东西:
select (case when code is not null
then row_number() over (partition by (case when code is not null then 1 else 0 end)
order by . . .
)
end) as id
我不清楚order by
row_number()
对. . .
的意义是什么。
答案 1 :(得分:0)
您可以在所需的子集上使用row_number,然后将所有其他记录合并:
select row_number() over (order by sortkey) as id, code, other_column
from mytable
where code is not null
union all
select null as id, code, other_column
from mytable
where code is null
order by sortkey;
答案 2 :(得分:0)
如果您需要在最后使用NULL的代码(在您的示例中为后代)订购:
select
decode(code,null,null,row_number() over (order by code DESC NULLS LAST)) rn,
code
from test;
如果您需要在OTHER列上订购:
select
decode(code,null,null,row_number() over (order by decode(code,null,null,'x') NULLS LAST, other DESC)) rn,
code, other
from test;
答案 3 :(得分:0)
另一种简单的方法是:
Select
CASE WHEN code IS NOT NULL THEN ROW_NUMBER() OVER (PARTITION BY code order by code)
ELSE NULL END id,
code,
other_column
FROM table;