0

我有一个类似这样的登录表:

表日志

date      |  time   | event      | program   | ordendate
20130722    070000    executing    program1    20130722
20130722    070040    end ok       program1    20130722
20130722    070100    executing    program1    20130722
20130722    070140    end ok       program1    20130722

我有一个查询

 select a.date || a.time as datetimeStart, 
        b.date || b.time as datetimeStop, 
        a.program, a.ordendate  
   from tablelog a, 
        tablelog b
  where a.date || a.time < b.date || b.time
    and a.event = "executing"
    and b.event = "end ok"

这会返回 3 次执行,但只有我有 2 次……我该如何解决这个查询???

谢谢!!

4

3 回答 3

1

您尝试执行的查询最好使用分析函数lag()lead()

select dateTimeStart, dateTimeStop, program, orderdate
from (select tl.date || tl.time as datetimeStart,
             lead(tl.date || tl.time) over (partition by program order by date, time) as dateTimeStop,
             tl.*
      from tablelog tl
     ) tl
where tl.event = 'Executing';
于 2013-07-22T16:06:33.007 回答
1

据我了解,您想按程序列出顺序启动/停止(?)这用于LEAD在 a 中完成工作CTE,然后仅使用外部查询进行过滤和排序;

WITH cte AS (
  SELECT 
    CASE WHEN "event"='executing' THEN "date" || "time" END "datetimeStart",
    LEAD(CASE WHEN "event"='end ok' THEN "date" || "time" END) 
    OVER(PARTITION BY "program" ORDER BY "date","time") "datetimeStop",
    "program", "ordendate"
  FROM tablelog
)
SELECT * FROM cte
WHERE "datetimeStart" IS NOT NULL 
  AND "datetimeStop"  IS NOT NULL
ORDER BY "datetimeStart"

一个用于测试的 SQLfiddle

于 2013-07-22T16:18:56.400 回答
0

我认为,以上将返回以下 3 条记录:-

  1. 第一条记录与第二条记录匹配
  2. 第一条记录与第四条记录匹配
  3. 第三条记录与第四条记录相匹配。

要解决此问题,请尝试以下查询(未经测试):-

select * from
(select a.date || a.time as datetimeStart, 
        b.date || b.time as datetimeStop, 
        a.program, a.ordendate, row_number() over (partition by (a.date || a.time) order by (a.date || a.time)) rn  
   from tablelog a, 
        tablelog b
  where a.date || a.time < b.date || b.time
    and a.event = "executing"
    and b.event = "end ok")
where rn =1
于 2013-07-22T16:09:05.290 回答