简体   繁体   English

如何在几天内迭代选择语句

[英]How to iterate a select statement over a range of days

I need to iterate a select statement over a range of days. 我需要在几天内迭代一次select语句。 The purpose is to get the volume of open records in our various groups at a moment in time each day in the past year, by using the open and close time stamps of the records. 目的是通过使用记录的打开和关闭时间戳记来获取过去一年中每天的某个时间在各个组中打开的记录的数量。 The select statement is something like this: select语句是这样的:

select I.INC_GROUP, count(I.INC_GROUP) as INC_VOLUME
from XXX.INCIDENT i
where
I.OPEN_TIME < to_date('2015/09/21 08:00:00', 'YYYY/MM/DD HH24:MI:SS') and
I.CLOSE_TIME > to_date('2015/09/21 08:00:00', 'YYYY/MM/DD HH24:MI:SS')
group by I.INC_GROUP

I am trying to iterate it for 8AM today-366 to 8AM today-1. 我正尝试将其从今天(今天)上午8点(366)迭代到今天(今天上午8点)。 My output would be inserted into a table and would consist of the INC_GROUP, INC_VOLUME, and the date of the iteration (first record would be 22-SEP-14 08:00:00). 我的输出将插入到一个表中,并将由INC_GROUP,INC_VOLUME和迭代日期组成(第一条记录为22-SEP-14 08:00:00)。

Use a CONNECT BY to generate a set of numbers and use these in conjunction with date logic (DATE + 1 will add a day). 使用CONNECT BY生成一组数字,并将其与日期逻辑结合使用(DATE + 1将增加一天)。 This will generate you a row for each day. 这将每天为您生成一行。

SELECT TRUNC(SYSDATE - LEVEL) + (1/24*8)
FROM dual
CONNECT BY LEVEL <= 365

This can then be incorporated to another data set, for example: 然后可以将其合并到另一个数据集中,例如:

WITH days AS (
  SELECT
    TRUNC(SYSDATE - LEVEL) + (1/24*8) day_start
  -- This adds a day to the above and removes a second
  , TRUNC(SYSDATE - LEVEL + 1) + (1/24*8) - (1/24/60/60) day_end    
  FROM dual
  CONNECT BY LEVEL <= 365
)
SELECT 
  days.day_start
, COUNT(yt.date_col) num
FROM days
LEFT JOIN your_table yt ON yt.date_col BETWEEN days.day_start AND days.day_end

This would give you a row for each day and a number of matching rows from your_table that fell between 8am and 7:59:59 the following day. 这将为您每天提供一行,并提供来自your_table的许多匹配行, your_table行在your_table上午8点至your_table之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM