row_number重置

时间:2013-04-09 11:24:52

标签: sql sql-server

我有一张桌子。

刺激,更改,约会
pr1,'是',2012-01-01
pr1,'不',2012-02-01
pr1,'不',2012-03-01
pr1,'是',2012-04-01
pr1,'是',2012-05-01
pr1,'不',2012-06-01

我正在尝试构建一个qry并使用row_number()函数来编号行。我只需要row_number()重置每次更改列的值为yes。然后row_number()计算必须从头开始。喜欢这个

prod,change,date,row_number
pr1,'是',2012-01-01, 1
pr1,'不',2012-02-01, 2
pr1,'不',2012-03-01, 3
pr1,'是',2012-04-01, 1
pr1,'是',2012-05-01, 1
pr1,'不',2012-06-01, 2
......等等。

是否有可能只使用SQL做类似的事情?我正在查看像row_number()这样的窗口函数(按日期排序,prd_prod,更改),但它不能像那样工作。还有其他选择吗?

3 个答案:

答案 0 :(得分:2)

为了重置row_number,你必须添加" PARTITION BY"

在:

select RowOrder=ROW_NUMBER() OVER (ORDER BY WidgetTimeCreated)

后:

select RowOrder=ROW_NUMBER() OVER (PARTITION BY WidgetType ORDER BY WidgetTimeCreated)

答案 1 :(得分:1)

select *, row_number() over (partition by prod, 
                                (case when change = 'No' then (select max(date) from [<YourTable>] where prod = d.prod and change = 'Yes' and date < d.date)
                                      else date end) order by date) as rownum
from [<YourTable>] d

答案 2 :(得分:1)

尝试:

with yes as
(select y.*, row_number() over (partition by prod order by date) yesn
 from mytable y
 where change = 'Yes'),
yesrange as
(select c.*, n.[date] next_date
 from yes c
 left join yes n on c.prod = n.prod and c.yesn+1 = n.yesn)
select m.*, row_number() over (partition by m.prod, r.yesn order by m.date)
from mytable m
join yesrange r 
  on m.prod = r.prod and 
     m.[date] >= r.date and
     m.[date] < coalesce(r.next_date, dateadd(d, 1, m.[date]) )

(SQLFiddle here