选择具有异常分组的查询

时间:2014-06-20 11:14:48

标签: sql sql-server database tsql select

有一张包含以下数据的表格(即):

SELECT * FROM Fruits

StartDate   EndDate     Information
------------------------------------
1992-09-01  1998-10-28  Cherry
1998-10-29  1998-12-30  Peach
1999-01-01  2000-01-31  Peach
2000-02-01  2000-06-30  Peach
2000-07-01  2001-01-31  Peach
2001-02-01  2002-03-31  Cherry
2002-04-01  2003-03-31  Carrot
2003-04-01  2003-05-20  Carrot
2003-05-21  2004-03-31  Apple
2004-04-01  2004-06-30  Apple
2004-07-01  2005-07-31  Apple
2005-08-01  2006-10-31  Apple
2006-11-01  2007-01-31  Apple
2007-02-01  2007-06-30  Apple
2007-07-01  2008-02-29  Apple
2008-03-01  2008-05-31  Apple
2008-06-01  2009-02-28  Apple
2009-03-01  2010-03-31  Apple
2010-04-01  2010-12-31  Apple
2011-01-01  2011-07-31  Apple
2011-08-01  2012-01-31  Apple
2012-02-01  2013-05-31  Apple
2013-06-01  2013-09-30  Apple
2013-10-01  2013-12-31  Apple

我必须进行查询,返回类似的内容:

StartDate   EndDate     Information
------------------------------------
1992-09-01  1998-10-28  Cherry
1998-10-29  2001-01-31  Peach
2001-02-01  2002-03-31  Cherry
2002-04-01  2003-05-20  Carrot
2003-05-21  2013-12-31  Apple

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要在一个组中的每个information的顺序值。

您可以通过为值分配组号来完成此操作。实现此目的的一种方法是在所有行上获取序列号的差异,并为每个information值重新启动序列号。然后聚集在这个组:

select min(startdate) as startdate, max(enddate) as enddate, information
from (select f.*,
             (row_number() over (order by startdate) -
              row_number() over (partition by information order by startdate)
             ) as grp
      from fruits f
     ) f
group by grp, information;