Sql时间范围计数与平均值和公式

时间:2014-04-02 08:21:04

标签: sql postgresql

SQl查询返回特定时间值范围和计数

select
res.range, count(*)
from (select 
CASE WHEN t1.response_time between 0 and 4 then 'Within 4 Hours' 
WHEN t1.response_time between 4 and 6 then '4-6 Hours' 
WHEN t1.response_time between 6 and 8 then '6-8 Hours'
WHEN t1.response_time > 8 then  '8+ Hours'
END as range
from table1 t1) as res
group by res.range

以下SQl查询返回特定时间值范围和计数

   Range        | Count
 ----------------------
  4-6 Hours     |  24
  8+ Hours      |  23
  6-8 Hours     |  22
  Within 4 Hours|  7

预期产出

  Range        | Count
----------------------
 4-6 Hours     |  24
 8+ Hours      |  23
 6-8 Hours     |  22
 Within 4 Hours|  7
 Average       |  x  (Average of Range Time Count)

在最后一行的范围内,我想显示平均和平均范围时间计数。如何显示最后一行平均值以及计算范围平均时间计数的公式是什么。

2 个答案:

答案 0 :(得分:1)

试试这个

select
res.range, count(*)
from (select 
CASE WHEN t1.response_time between 0 and 4 then 'Within 4 Hours' 
WHEN t1.response_time between 4 and 6 then '4-6 Hours' 
WHEN t1.response_time between 6 and 8 then '6-8 Hours'
WHEN t1.response_time > 8 then  '8+ Hours'
END as range
from table1 t1) as res
group by res.range
union all
select 'Average', AVG(counting) from
(
select
res.range, count(*) as counting
from (select 
CASE WHEN t1.response_time between 0 and 4 then 'Within 4 Hours' 
WHEN t1.response_time between 4 and 6 then '4-6 Hours' 
WHEN t1.response_time between 6 and 8 then '6-8 Hours'
WHEN t1.response_time > 8 then  '8+ Hours'
END as range
from table1 t1) as res
group by res.range
) t

答案 1 :(得分:0)

您可以使用with rollup技巧执行此操作:

select coalesce(res.range, 'Total') as range, avg(cnt) as cnt
from (select res.range, count(*) as cnt
      from (select (CASE WHEN t1.response_time between 0 and 4 then 'Within 4 Hours' 
                         WHEN t1.response_time between 4 and 6 then '4-6 Hours' 
                         WHEN t1.response_time between 6 and 8 then '6-8 Hours'
                         WHEN t1.response_time > 8 then  '8+ Hours'
                    END) as range
           from table1 t1
          ) res
      group by res.range
     ) r
group by res.range with rollup;

外部group by排序对现有行没有任何作用 - 单个值的平均值就是该值。但它应该与平均值一致。