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,256 of 19,505   
   Erland Sommarskog to Henk van den Berg   
   Re: Help needed to write a qury   
   25 Apr 11 10:14:20   
   
   From: esquel@sommarskog.se   
      
   Henk van den Berg (hvandenberg@xs4all.nl) writes:   
   > On 24-04-2011 21:51, Erland Sommarskog wrote:   
   >> WITH numbered AS (   
   >>     SELECT EmpID, EmpName, DepartmentID, AllocationDate,   
   >>            rowno = row_number() OVER(PARTITION BY EmpID   
   >>                                      ORDER BY AllocationDate)   
   >> )   
   >> 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   
   >> ORDER  BY a.EmpId, a.rowno   
   >   
   > If I copy/paste and run this code, it complains about invalid columnnames.   
   > I do notice that there's no reference to a table in the AS (SELECT   
   > EmpId...) part, but when I put in the name of the table that I created,   
   > I get those invalid columnname errors as well.   
   > I'm sure I'm forgetting something very basic, but I can't get it to run.   
   > What am I overlooking?   
      
   I forgot the FROM clause in the CTE:   
      
   WITH numbered AS (   
      SELECT EmpID, EmpName, DepartmentID, AllocationDate,   
             rowno = row_number() OVER(PARTITION BY EmpID   
                                       ORDER BY AllocationDate)   
      FROM   tbl   
   )   
   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   
   ORDER  BY a.EmpId, a.rowno   
      
   Had Dinesh posted CREATE TABLE statement for his table and INSERT statements   
   with sample data, I would have been able to test my query. Now I wasn't.   
      
      
   --   
   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