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 17,650 of 19,505   
   Erland Sommarskog to Plamen Ratchev   
   Re: Can this be done in a single query?   
   24 Sep 09 21:26:27   
   
   From: esquel@sommarskog.se   
      
   Plamen Ratchev (Plamen@SQLStudio.com) writes:   
   > It will be best to post sample data and the expected results.   
   >   
   > Try this:   
   >   
   > SELECT id, unit_id, counter   
   > FROM (   
   > SELECT id, unit_id, counter,   
   >         ROW_NUMBER() OVER(PARTITION BY unit_id ORDER BY counter) AS rk   
   > FROM Table) AS T   
   > WHERE rk <= 6;   
      
   Or maybe this is what Billy is looking for:   
      
    SELECT id, unit_id, counter   
    FROM (   
    SELECT id, unit_id, counter,   
            RANK() OVER(PARTITION BY unit_id ORDER BY counter) AS rk   
    FROM Table) AS T   
    WHERE rk = 1;   
      
   I think there are two ways that Billy can reach his goal. One is that   
   he studies the row_number, rank and dense_rank functions, working from   
   our examples.   
      
   The other is that he, as Plamen suggests, posts:   
      
   o   CREATE TABLE statements for his table.   
   o   INSERT statements with sample data.   
   o   The desired result given the sample.   
      
      
   --   
   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   
   SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx   
      
   --- 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