sql - Group by column and select range of each group -
id refid date1 date2 nextdate 5 10 2008-02-21 2009-02-21 004/2008 6 10 2009-02-09 2010-02-09 002/2009 7 10 2010-02-08 2011-02-08 001/2010 10 11 2007-02-15 2008-02-15 002/2007 11 11 2008-02-21 2009-02-21 001/2008 12 11 2009-02-09 2010-02-09 001/2009 13 11 2010-02-09 2011-02-09 002/2010 14 11 2011-07-19 2012-07-19 054/2011 15 11 2012-07-17 2013-07-17 066/2012 18 14 2007-02-15 2008-02-15 006/2007 25 16 2007-02-15 2008-02-15 004/2007 27 16 2009-02-10 2010-02-10 004/2009 28 16 2010-02-12 2011-02-12 005/2010 29 16 2011-07-26 2012-07-26 055/2011 30 16 2012-07-18 2013-07-18 067/2012
i have datatable. need filter datatable following contitions. if refid have more 4 same values need first 1 , last 3. if have 4 , less same refid valuses nothing. result should this:
id refid date1 date2 nextdate 5 10 2008-02-21 2009-02-21 004/2008 6 10 2009-02-09 2010-02-09 002/2009 7 10 2010-02-08 2011-02-08 001/2010 10 11 2007-02-15 2008-02-15 002/2007 13 11 2010-02-09 2011-02-09 002/2010 14 11 2011-07-19 2012-07-19 054/2011 15 11 2012-07-17 2013-07-17 066/2012 18 14 2007-02-15 2008-02-15 006/2007 25 16 2007-02-15 2008-02-15 004/2007 28 16 2010-02-12 2011-02-12 005/2010 29 16 2011-07-26 2012-07-26 055/2011 30 16 2012-07-18 2013-07-18 067/2012
how that?
you can use row_number
in cte
:
with cte as( select [id], [refid], [date1], [date2], [nextdate], rn_asc = row_number()over( partition refid order id asc), rn_desc = row_number()over( partition refid order id desc) dbo.mytable ) select [id], [refid], [date1], [date2], [nextdate] cte rn_asc = 1 or rn_desc <= 3 order [id]
Comments
Post a Comment