【问题标题】:Select query with unusual grouping选择具有异常分组的查询
【发布时间】:2014-08-11 03:18:15
【问题描述】:

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: sql sql-server database tsql select


    【解决方案1】:

    如果我理解正确,您希望每个 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;
    

    【讨论】:

    • 我仍然无法理解如何,但它可以工作。比你!
    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 2012-06-27
    • 2021-01-06
    相关资源
    最近更新 更多