I am trying to write a sql query that pulls an ID and concatenates the max times within 15 minute time intervals starting from the first time.
i.e. for one log_id data might be
101 01:01
101 01:08
101 01:23
101 02:01
101 02:10
101 02:16
we would want to display
101 01:01, 01:08, 01:23, 2:01, 2:16
any ideas?
here is the starting query we are using:
select
ol.log_id,
ifm.meas_value,
ifm.measure_id,
ifm.recorded_time
from meas ifm
inner join rec ifr on ifm.fsd_id = ifr.fsd_id
inner join pe on ifr.data_id = pe.data_id
inner join record_summary f on pe.n_id = f.n_id
inner join pe2 on pe.t_id = pe2.t_id and pe.date = pe2.date and pe2.type = 51
inner join log l on pe2.ata_id = l.data_id and l.date = pe2.date
where ifm.measure_id in ('891')
and ol.date >= trunc(sysdate - 3)
for each log_id there will be multiple recorded times we want to pull the first time, and the maximum time in every 15 minute interval until the last time. These times will be concatenated to a list.
We tried a listagg with all the values, but there are too many times so the end-user wants to only see one value for every 15 minutes.
答案 0 :(得分:0)
基本上你有三个问题在一个:
如何将日期字段舍入到15分钟? https://community.oracle.com/thread/1042863
ceil(to_number(to_char(test_timestamp,' yyyymmddhh24mi'))/ 15)* 15
如何从群组中获取行?
这是一个非常受欢迎的问题,你会在这里找到一些东西: https://stackoverflow.com/questions/tagged/oracle+greatest-n-per-group?sort=votes&pageSize=30
如何聚合字符串值以在组内连接:
LISTAGG(convertedTimeField,'')
尝试在一个查询中组合所有三个部分以获得所需的结果。
答案 1 :(得分:0)
简化使用下表:
CREATE TABLE Test ( id NUMBER, log DATE );
(注意:oracle中的DATE
实际上是dateTime。字符串连接是用||
完成的。)
您的给定列表似乎表明,当最大值和最小值相同时您只显示一次,这可以通过分组两次来完成:
SELECT
O.id,
O.logDate,
LISTAGG(O.logTimes, ', ') WITHIN GROUP (ORDER BY O.logTimes) logTimes
FROM (
SELECT
O.id,
O.logDate,
O.G G,
CASE
WHEN TO_CHAR(MIN(O.log), 'HH24:MI') <> TO_CHAR(MAX(O.log), 'HH24:MI') THEN
TO_CHAR(MIN(O.log), 'HH24:MI') || ', ' || TO_CHAR(MAX(O.log), 'HH24:MI')
ELSE
TO_CHAR(MIN(O.log), 'HH24:MI')
END logTimes
FROM (
SELECT
T.id,
T.log,
TRUNC(T.log) logDate,
TO_CHAR(T.log, 'HH24') || FLOOR(TO_NUMBER(TO_CHAR(T.log, 'MI')) / 15) G
FROM
Test T
) O
GROUP BY
O.id, O.logDate, O.G
) O
GROUP BY
O.id, O.logDate
;
请参阅SQL fiddle。