2012-09-13 71 views
1

我對某些數據做了row_number()如何在做row_number時不計0 0

我的問題是,我不想考慮數據是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都不計入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 
+0

謝謝我非常想嘗試一下。只是爲了向您確認,row_number不會考慮number = 0的值嗎? –

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 
+1

可愛的第二個查詢。你是絕對正確的。 –

+0

@lc。你是絕對正確的,它很可愛 –