home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.databases.ms-sqlserver      Notorious Rube Goldberg contraption      19,505 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 18,258 of 19,505   
   Erland Sommarskog to Erland Sommarskog   
   Re: Help needed to write a qury   
   25 Apr 11 15:31:25   
   
   From: esquel@sommarskog.se   
      
   Erland Sommarskog (esquel@sommarskog.se) writes:   
   > Thanks for the sample data!   
   >   
   > I see that I had forgot the join condition on EmpId - without the query is   
   > kind of meaningless.   
   >   
   > The principle is simple: number the rows, and then make a self-join on   
   > the row number with the next number.   
      
   Pressed Send to quickly! Here is the query:   
      
   WITH numbered AS (   
      SELECT EmpId, EmpName, DepartmentID, AllocationDate,   
             rowno = row_number() OVER(PARTITION BY EmpId   
                                       ORDER BY AllocationDate)   
      FROM   EmployeeDept   
   )   
   SELECT a.EmpId, a.EmpName, a.DepartmentID AS OldDeptID,   
          b.DepartmentID AS NewDeptID, a.AllocationDate,   
          b.AllocationDate AS TransferDate   
   FROM   numbered a   
   JOIN   numbered b ON b.rowno = a.rowno +1   
                    AND b.EmpId = a.EmpId   
   ORDER  BY a.EmpId, a.rowno   
      
      
   --   
   Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se   
      
   Links for SQL Server Books Online:   
   SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx   
   SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca