2

如何从多个 dateBegin 和 dateEnd 中获取“最大”日期范围?我的问题没有得到很好的解释(因为我不是英语),但下面的示例将向您展示我的期望。

我的数据库:

在此处输入图像描述

我想要的输出:

id_master    beginDate    endDate
13           26/07/2014   30/08/2014
280          28/09/2013   01/10/2013
280          01/04/2014   11/04/2014

说明:对于不同的 id_master,我希望不同的日期周期由最小 beginDate 和最大 endDate 组成,这些日期之间的所有天都有一个产品(表中的行)

当前查询:

SELECT DISTINCT campings.id_master, CAST(campings.dateBegin AS DATETIME) AS beginDate, CAST(campings.dateEnd AS DATETIME) AS endDate
FROM         campings 
ORDER BY id_master, beginDate, endDate

PS:日期格式为dd/mm/yyyy

4

3 回答 3

3

这可能比它必须做的要人为得多,其他人可以想出一个更简单的答案,但您可以尝试以下方法:

WITH ordered AS (
  SELECT a.id_master, a.beginDate, a.endDate, 
      ROW_NUMBER() OVER(PARTITION BY id_master ORDER BY beginDate, endDate) AS rn
  FROM Table1 a
), Adjacent AS (
  SELECT a.id_master, a.beginDate, a.endDate, a.rn
  FROM ordered a
  UNION ALL
  SELECT a.id_master, a.beginDate, b.endDate, b.rn
  FROM Adjacent a
  INNER JOIN ordered b ON a.id_master = b.id_master AND b.rn > a.rn 
      AND a.endDate >= b.beginDate
), resolvedEnd AS (
  SELECT a.id_master, a.beginDate, MAX(a.endDate) AS endDate
  FROM Adjacent a
  GROUP BY a.id_master, a.beginDate
)
SELECT a.id_master, MIN(beginDate) AS beginDate, endDate
FROM resolvedEnd a
GROUP BY a.id_master, a.endDate

SQL 小提琴示例

这样做是首先为每一行附加一个升序的行号,以确保我们只在前向递归。然后它设置一个递归 CTE 来关联重叠行(以及重叠行的重叠行)。然后它解析每个开始日期的最大结束日期,然后解析每个结束日期的最早开始日期。

于 2013-10-08T15:32:35.933 回答
0

对于其他人,这是我当前需求的结果。在Informix 11.70及更高版本上,此构造具有相同的结果:


SELECT id_master , MIN(beginDate) AS beginDate, endDate FROM
  LATERAL (
    SELECT id_master, beginDate, MAX(endDate) AS endDate FROM
      LATERAL (
        SELECT id_master, beginDate, CONNECT_BY_ROOT endDate FROM
          LATERAL (
            SELECT id_master, beginDate, endDate, ROW_NUMBER() OVER(PARTITION BY id_master ORDER BY beginDate, endDate) AS row_num FROM campings
          ) AS ordered
          CONNECT BY
            PRIOR id_master = id_master AND
            PRIOR row_num > row_num AND
            PRIOR endDate + 1 >= beginDate AND
            PRIOR beginDate - 1 <= endDate
      ) AS Adjacent
      GROUP BY id_master, beginDate
  ) AS resolvedEnd
  GROUP BY id_master, endDate

于 2017-02-17T14:58:38.650 回答
-1
SELECT DISTINCT 
    id_master, 
    MIN (beginDate) OVER (PARTION BY id_master) beginDate, 
    MAX(endDate) OVER (PARTION BY id_master) endDate 
FROM campings 
于 2013-10-08T15:56:15.137 回答