SQL Server-ROW_NUMBER()->重新重置?

时间:2019-03-20 10:50:25

标签: sql sql-server window-functions

我们正在编写的查询中遇到一个特定的问题。 这是示例:

Doc. ID | Timestamp | Employee 
 01     | 01        | A        
 01     | 02        | B        
 01     | 03        | B        
 01     | 04        | C        
 01     | 05        | A        
 01     | 06        | A       

我们想要实现的是:

Doc. ID | Timestamp | Employee 
 01     | 01        | A        
 01     | 03        | B        
 01     | 04        | C        
 01     | 06        | A      

这是我们的方法(无效):

SELECT [Doc. ID], [Timestamp], [Employee]
       ,ROW_NUMBER() OVER (PARTITION BY [Doc. ID],[Employee] order by [Employee] desc) as "RN"
FROM XY
WHERE "RN" = 1

但是不幸的是,这行不通,因为当再次在底部找到A时,Row_number不会重置。我们收到的结果(没有where子句)是:

 Doc. ID | Timestamp | Employee | RN
  01     | 01        | A        | 1
  01     | 02        | B        | 1
  01     | 03        | B        | 2
  01     | 04        | C        | 1
  01     | 05        | A        | 2
  01     | 06        | A        | 3

我认为仅是实现正确解决方案而已。.:)

2 个答案:

答案 0 :(得分:4)

使用lead()达到“下一个”行中员工价值的峰值:

select xy.*
from (select xy.*,
             lead(employee) over (partition by docid order by timestamp) as next_employee
      from xy
     ) xy
where next_employee is null or next_employee <> employee;

答案 1 :(得分:2)

我认为您想要聚合:

SELECT [doc. ID], MAX([Timestamp]) AS [Timestamp], employee
FROM (SELECT t.*,
             row_number() over (order by [Timestamp]) as seq1,
             row_number() over (partition by [doc. ID], employee order by [Timestamp]) as seq2
      FROM XY t
     ) t
GROUP BY [doc. ID], employee, (seq1 - seq2)
ORDER BY [Timestamp];