Oracle时间间隔桶

时间:2013-10-02 12:27:36

标签: sql if-statement oracle11g case

select TRANSACTION, comp_time, start_time, (comp_time - start_time) as DIFF from table
where start_time = trunc(sysdate) 

我想根据DIFF值计算,在相同的sql语句中,在不到10秒,1分钟和15分钟内完成了多少次TRANSACTION。 我是SQL的新手..也许我们可以使用一些if-else或一些CASE条件.. 在获得每个值的计数后,我需要计算每个值的百分比..

假设我总共有3000次交易,其中1500次在不到10秒内完成。百分比将是50% 同样的事情也是1分钟和15分钟。

2 个答案:

答案 0 :(得分:2)

标准化结果Oracle版本,使用分析函数计算百分比。

with cte_durations as (
  select
    case when (comp_time - start_time) * 24 * 60 * 60 < 10 then '< 10 sec'
         when (comp_time - start_time) * 24 * 60 * 60 < 60 then '< 1 min'
         when (comp_time - start_time) * 24 * 60      < 15 then '< 15 min'
         else                                                   '>= 15 min'
    end duration_bucket
  from  table
  where    start_time = trunc(sysdate))
select   duration_bucket,
         count(*),
         100*ratio_to_report(count(*)) over () pct_of_total
from     cte_durations
group by duration_bucket
order by case duration_bucket         
           when '< 10 sec'  then 1
           when '< 1 min'   then 2
           when '< 15 min'  then 3
           when '>= 15 min' then 4
         end
/

答案 1 :(得分:1)

for SQL Server:

with timecounts as (
    select count(case when datediff(ss, start_time, comp_time) <= 10 then transactionId end) as q10s,
           count(case when datediff(ss, start_time, comp_time) <= 60 then transactionId end) as q1m,
           count(case when datediff(mi, start_time, comp_time) <= 15 then transactionId end) as q15m,
           count(*) qTotal   
    from   table
    where  start_time = trunc(sysdate)
    )

select q10s,
       q1m,
       q15m,
       case when qTotal <> 0 then cast(q10s as float) / qTotal end as q10sPerc,
       case when qTotal <> 0 then cast(q1m as float) / qTotal end as q1mPerc,
       case when qTotal <> 0 then cast(q15m as float) / qTotal end as q15mPerc
from   TimeCounts

for oracle:

with timecounts as (
    select count(case when (comp_time - start_time) * 86400 <= 10 then transactionId end) as q10s,
           count(case when (comp_time - start_time) * 86400 <= 60 then transactionId end) as q1m,
           count(case when (comp_time - start_time) * 1440 <= 15 then transactionId end) as q15m,
           count(*) qTotal   
    from   myTable
    where  start_time = trunc(sysdate)
    )

select q10s,
       q1m,
       q15m,
       case when qTotal <> 0 then cast(q10s as float) / qTotal end as q10sPerc,
       case when qTotal <> 0 then cast(q1m as float) / qTotal end as q1mPerc,
       case when qTotal <> 0 then cast(q15m as float) / qTotal end as q15mPerc
from   TimeCounts