1

我正在做row_number()一些数据。

我的问题是我不想考虑0.

这是我的数据样本:

+-----------+-----+
| Alex      |   1 |
| Liza      |   2 |
| Harry     |   0 |
| Marge     |  24 |
| Bla       |   0 |
| Something | 234 |
+-----------+-----+

这就是我想要的:

+-----------+--------+------------+
|   name    | number | row_number |
+-----------+--------+------------+
| Harry     |      0 |          0 |
| Bla       |      0 |          0 |
| Something |    234 |          1 |
| Marge     |     24 |          2 |
| Liza      |      2 |          3 |
| Alex      |      1 |          4 |
+-----------+--------+------------+

如您所见,第三列是the row_number()

这就是我到目前为止所拥有的:

select name, number, row_number() over (partition by name order by name,number)
from myTable

如何让上面的查询返回源数据中的0所有内容,并且根本不将 0 计入 row_number 序列0's

4

2 回答 2

4

试试这个SQL 小提琴

SELECT name, number, 0 as [row_number]
FROM myTable
WHERE number = 0
UNION ALL
SELECT name, number, row_number() OVER (ORDER BY number DESC)
FROM myTable
WHERE number <> 0
于 2012-09-13T19:32:40.853 回答
2

试试这个:

select name, number,
       (case when number = 0 then 0
             else row_number() over (partition by iszero order by number desc)
        end) as row_number
from (select t.*, (case when number = 0 then 0 else 1 end) as iszero
      from myTable t
     ) t

由于您按数字降序排序,因此如果没有数字为负数,则以下工作:

select name, number,
       (case when number = 0 then 0
             else row_number() over (order by number desc)
        end) as row_number
from myTable t
于 2012-09-13T19:35:35.887 回答