Trouble using ROW_NUMBER() OVER (PARTITION BY …)

后端 未结 3 788
花落未央
花落未央 2021-02-02 14:43

I\'m using SQL Server 2008 R2. I have table called EmployeeHistory with the following structure and sample data:

EmployeeID Date      DepartmentID SupervisorID
1         


        
3条回答
  •  Happy的楠姐
    2021-02-02 15:31

    I would do something like this:

    ;WITH x 
     AS (SELECT *, 
                Row_number() 
                  OVER( 
                    partition BY employeeid 
                    ORDER BY datestart) rn 
         FROM   employeehistory) 
    SELECT * 
    FROM   x x1 
       LEFT OUTER JOIN x x2 
                    ON x1.rn = x2.rn + 1 
    

    Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

提交回复
热议问题