首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有平均值和公式的Sql时间范围计数

具有平均值和公式的Sql时间范围计数
EN

Stack Overflow用户
提问于 2014-04-02 16:21:04
回答 2查看 222关注 0票数 0

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

代码语言:javascript
运行
复制
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查询返回时间值和计数的特定范围

代码语言:javascript
运行
复制
   Range        | Count
 ----------------------
  4-6 Hours     |  24
  8+ Hours      |  23
  6-8 Hours     |  22
  Within 4 Hours|  7

预期输出

代码语言:javascript
运行
复制
  Range        | Count
----------------------
 4-6 Hours     |  24
 8+ Hours      |  23
 6-8 Hours     |  22
 Within 4 Hours|  7
 Average       |  x  (Average of Range Time Count)

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

EN

回答 2

Stack Overflow用户

发布于 2014-04-02 16:25:06

尝尝这个

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2014-04-02 16:25:27

您可以使用with rollup技巧来完成此操作:

代码语言:javascript
运行
复制
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排序对现有行没有任何作用--单个值的平均值就是该值。但它应该与平均值的总和一致。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22805484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档