简体   繁体   English

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

[英]SQL Server - ROW_NUMBER() -> Reset again?

we are facing a specific problem in a query we're currently writing. 我们正在编写的查询中遇到一个特定的问题。 Here is the example: 这是示例:

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

What we want to achieve is that: 我们想要实现的是:

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

This was our approach (which didn't work): 这是我们的方法(不起作用):

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

But unfortunately that doesn't work, because the Row_number does not reset when finding A again at the bottom. 但不幸的是,这行不通,因为当再次在底部找到A时,Row_number不会重置。 It The result we receive (without the where clause) is: 它我们收到的结果(没有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

I think it's only a little bit more to achieve the right solution.. :) 我认为仅是实现正确解决方案而已。

Use lead() to peak at the employee value in the "next" row: 使用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;

I think you want aggregation : 我认为您想要聚合:

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]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM