根据当前值获得下一个更高的值

时间:2018-09-17 14:19:19

标签: sql sql-server group-by window-functions

我正在尝试从日志中获取下一个审核ID,但是对于每个AuditID都获取了多个NextAuditID。

几个问题:

  1. 该如何纠正?
  2. 这是最有效的方法吗?

我的代码:

SELECT DISTINCT 
    AuditID, MIN(NextAuditID) NextAuditID
FROM
    (SELECT 
         SMStart.AuditID AuditID, SMNext.AuditID NextAuditID
     FROM 
         SchedulerMetrics SMStart,
         SchedulerMetrics SMNext
     WHERE 
         SMStart.Message = SMNext.Message
         AND SMNext.AuditID > SMStart.AuditID) tt
GROUP BY 
    AuditID, NextAuditID

1 个答案:

答案 0 :(得分:3)

您可以使用LEAD窗口功能:

SELECT AuditID, LEAD(AuditID) OVER (PARTITION BY Message ORDER BY AuditID) AS NextAuditID
FROM SchedulerMetrics