在Oracle中,row_number()函数是否可以忽略null值?

3
我有这样的数据
---------------------------
|   code    | other column
---------------------------
|   C       |    a
|   null    |    a
|   A       |    a
|   null    |    a
|   null    |    a
----------------------------

如何编写查询以获取行号,而无需计算空列。

----------------------------------
| id  |   code    | other column |
----------------------------------
| 1   |   C       |    a
|     |   null    |    a
| 2   |   A       |    a
|     |   null    |    a
|     |   null    |    a
----------------------------------
5个回答

8
好的,不是特别准确。但是您可以通过使用条件逻辑来获得所需结果:
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

我不清楚row_number()order by是什么意思,也不知道. . .代表什么。


1
如果您需要按代码(在您的示例中是降序)排序,并将NULL排在最后:
select 
  decode(code,null,null,row_number() over (order by code DESC NULLS LAST)) rn,
  code
from test;

如果您需要按照其他列进行订购:

select 
  decode(code,null,null,row_number() over (order by decode(code,null,null,'x')  NULLS LAST, other DESC)) rn,
  code, other
from test;

1

另一种简单的方法是:

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;

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;

0

例如,在我的情况下,使用“IS NOT NULL”对我没有起作用,我不得不将其更改为一个表达式:

SELECT A.ITEMNAME,
       CASE
          WHEN (SELECT T1.MAXSTOCK
                  FROM DATOS T1
                 WHERE T1.MAXSTOCK) > 5 THEN
           ROW_NUMBER() OVER(PARTITION BY CASE
                               WHEN (SELECT T1.MAXSTOCK
                                       FROM DATOS T1
                                      WHERE T1.MAXSTOCK) <= 5 /*here should go IS NOT NULL*/
                                THEN
                                1
                             END ORDER BY A.ITEMNAME)
          ELSE
           NULL
        END AS #ROW
  FROM TABLE A

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接