按列分组并选择每个组的范围

时间:2013-09-04 09:40:29

标签: sql sql-server-2008 filtering

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

我有这个数据表。我需要通过以下方式过滤数据表。 如果refid有超过4个相同的值,那么我需要第一个和最后一个3.如果我有4个相同的refid值而不是什么。结果应该是这样的:

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

怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在ROW_NUMBER中使用CTE

WITH CTE AS(
  SELECT [id], [refid], [date1], [date2], [nextdate],
     RN_ASC = ROW_NUMBER()OVER(
           PARTITION BY refid
           ORDER BY id ASC),
      RN_DESC = ROW_NUMBER()OVER(
           PARTITION BY refid
           ORDER BY id DESC)
  FROM dbo.MyTable
)
SELECT [id], [refid], [date1], [date2], [nextdate] 
FROM CTE
WHERE RN_ASC = 1 OR RN_DESC <= 3
ORDER BY [id]

DEMO

Ranking Functions (Transact-SQL)