在做row_number时如何不计数0

时间:2012-09-13 19:29:02

标签: sql sql-server sql-server-2008 tsql

我正在对某些数据进行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's,而根据row_number序列完全不计算0?

2 个答案:

答案 0 :(得分:4)

试试这个SQL Fiddle

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

答案 1 :(得分: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