Get top 2 rows from each distinct field in a column in Microsoft SQL Server 2008 -


i have table named tblhumanresources in want collection of rows consists of 2 rows each distinct field in effectivedate column (order by: ascending):

tblhumanresources table

| empid | effectivedate |  company | description | 0-123 |    2014-01-23 | dfd comp | analyst | 0-234 |    2014-01-23 | abc comp | manager | 0-222 |    2012-02-19 | cdc comp | janitor | 0-213 |    2012-03-13 | cbb comp | teller | 0-223 |    2012-01-23 | cbb comp | teller 

and on.

any appreciated.

try use row_number() function n rows per group:

select *    (      select t.*,             row_number() on (partition effectivedate                                 order empid)              rownum      tblhumanresources t    ) t1 t1.rownum<=2 order effectivedate 

sqlfiddle demo

version without row_number() function assuming empid unique during day:

select *  tblhumanresources t t.empid in (select top 2                          empid                      tblhumanresources t2                    t2.effectivedate=t.effectivedate                    order empid) order effectivedate 

sqlfiddle demo


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -