Oracle - 帮助进行查询

时间:2011-07-14 15:14:10

标签: sql oracle analytics

我有以下格式的数据来源:

Event Type| Date
1         | 2011-07-14 09:00
1         | 2011-07-14 09:01
1         | 2011-07-14 09:02
2         | 2011-07-14 09:30
2         | 2011-07-14 09:31
1         | 2011-07-14 10:00
1         | 2011-07-14 10:01

事件类型按日期排序。我需要创建一个查询,它将显示使用事件时的日期范围,按日期排序。像这样:

Event Type | Date Range
1          | 2011-07-14 09:00 - 2011-07-14 09:02
2          | 2011-07-14 09:30 - 2011-07-14 09:31
1          | 2011-07-14 10:00 - 2011-07-14 10:01

你有任何提示吗?我认为这可能需要用分析函数完成,但我还没有能够提出一个像样的解决方案。

2 个答案:

答案 0 :(得分:2)

您还可以尝试以下方法:

WITH ranked AS (
  SELECT
    EventType,
    Date,
    ROW_NUMBER() OVER (ORDER BY Date) -
      ROW_NUMBER() OVER (PARTITION BY EventType ORDER BY Date) AS GroupID
  FROM Events
)
SELECT
  EventType,
  MIN(Date) AS StartDate,
  MAX(Date) AS EndDate
FROM ranked
GROUP BY
  GroupID,
  EventType
ORDER BY
  MIN(Date)

答案 1 :(得分:1)

我确信有更好的解决方案,但是这个呢?

WITH
  ordered_data AS
(
  SELECT ROW_NUMBER() OVER (ORDER BY Date) AS row_id, * FROM event_data
),
  [start_events] AS
(
  SELECT * FROM ordered_data  AS [start]
  WHERE NOT EXISTS (SELECT * FROM ordered_data WHERE row_id = [start].row_id - 1 AND event_type = [start].event_type)
),
  [end_events] AS
(
  SELECT * FROM ordered_data  AS [end]
  WHERE NOT EXISTS (SELECT * FROM ordered_data WHERE row_id = [end].row_id + 1 AND event_type = [end].event_type)
)

SELECT
  *
FROM
  [start_events]
INNER JOIN
  [end_events]
    ON [end_events].row_id = (SELECT MIN(row_id) FROM [end_events] WHERE row_id >= [start_events].row_id)

这也应该应对“组”中只有一个事件的情况;如(1,1,2,1,1)