用于分发的Oracle SQL查询

时间:2014-05-21 13:50:50

标签: sql oracle

我有一个包含PR_ID,PR_FROM,PR_TO列的表PROCESSES。 PR_ID是进程标识符和PR_FROM和PR_TO时间戳,用于定义进程何时开始以及何时完成。

现在我想创建一个Oracle SQL查询,它将表示持续0-1小时的进程数,持续1-2小时的进程数等等。如何创建这样的查询?

2 个答案:

答案 0 :(得分:1)

SELECT TRUNC((PR_FROM - PR_TO)*24),count(*)
FROM PROCESSES 
GROUP BY TRUNC((PR_FROM - PR_TO)*24)

编辑显示0个出现记录

with hours as (select level-1 as lev
               from dual
               connect by level <= (select max(trunc((pr_from - pr_to)*24))
                                    from processes
                                    ) + 1
              )
,    proctime as (select trunc((pr_from - pr_to)*24) as hours 
                  ,      count(*) as num
                  from processes
                  group by trunc((pr_from - pr_to)*24))   
select lev
,      nvl(num,0) from hours
left outer join proctime on (lev = hours)
order by 1;

答案 1 :(得分:0)

我自己找到答案(24小时内分发):

SELECT h,COUNT(pr_id) n
FROM (SELECT LEVEL AS h FROM DUAL CONNECT BY LEVEL <= 24)
LEFT JOIN processes ON h=(EXTRACT(HOUR FROM (PR_TO-PR_FROM))+1)
GROUP BY h
ORDER BY h

从0到最大值的分布:

SELECT h,COUNT(pr_id) n
FROM (SELECT LEVEL AS h FROM DUAL CONNECT BY LEVEL <= ((SELECT MAX(EXTRACT(HOUR FROM (PR_TO-PR_FROM))+1) FROM processes)))
LEFT JOIN processes ON h=(EXTRACT(HOUR FROM (PR_TO-PR_FROM))+1)
GROUP BY h
ORDER BY h
罗伯特帮了很多忙。