2016-12-14 167 views
0

如果我有以下的表称为stats计算总和,平均和DB 90%/ 2

type duration 
------ --------- 
get  10 
get  15 
get  20 
put  12 
put  14 
put  16 

我知道我能得到sum()average()用类似的查询:

select 
    type, 
    sum(duration) as "total duration", 
    avg(duration) as "average duration" 
from 
    stats 
group by 
    type 

而且我还可以使用窗口函数功能获得90%的持续时间和max()

select 
    type, 
    avg("dur") as "average duration of the fastest 90%", 
    max("dur") as "max duration of the fastest 90%" 
from 
(
    select 
     type, 
     duration as "dur", 
     row_number() over (partition by type order by duration asc) as "seqnum" 
     count(*) over (partition by type) as "totnum" 
    from 
     stats 
) 
where 
    "seqnum" <= (.9 * "totnum") 
group by 
    type 

但我很努力地了解如何将两者合并,以便我可以有一个查询返回:typetotal durationaverage duration,average duration of the fastest 90%,max duration of the fastest 90%

回答

2

使用条件汇总:

select type, 
     sum(duration) as "total duration", 
     avg(duration) as "average duration", 
     avg(case when "seqnum" <= (0.9 * "totnum") then "dur" end) as "average duration of the fastest 90%", 
     max(case when "seqnum" <= (0.9 * "totnum") then "dur" end) as "max duration of the fastest 90%" 
from (select type, duration as "dur", 
      row_number() over (partition by type order by duration asc) as "seqnum", 
      count(*) over (partition by type) as "totnum" 
     from stats 
    ) s 
group by type; 
+0

因此,'seqnum“<(0.9 *”totnum“)时的情况”then“dur”end“意思是”如果符合标准,那么在聚合函数中使用它,否则不要使用它? –

+1

@MattFelzani。 。 。基本上。它实际上意味着评估表达式; 'else'子句是'NULL'。大多数聚合函数忽略NULL值。 –

1

你可以试试这个。

select distinct 
    type, 
    avg("dur") over(partition by type) as "average duration of the fastest 90%", 
    max("dur") over(partition by type) as "max duration of the fastest 90%", 
    "total duration", 
    "average duration" 
from 
(
    select 
     type, 
     duration as "dur", 
     row_number() over (partition by type order by duration asc) as "seqnum", 
     count(*) over (partition by type) as "totnum", 
     sum(duration) over(partition by type) as "total duration", 
     avg(duration) over(partition by type) as "average duration" 
    from 
     stats 
) x 
where 
    "seqnum" <= (.9 * "totnum") 
+0

,但不会是给我的四个统计的仅仅是90%?我想要100%的总体和平均水平,其他两个只有90%? –

+0

它将为您提供100%的总计和平均值,因为在内部查询中给定类型的所有行的总和(持续时间)(按类型划分)和平均值(持续时间)(按类型划分)将相同。你可以运行内部查询并检查。 –

+0

啊,我刚刚看到那部分。这很酷。基本上*所有行都带有这两个100%的字段。 一旦我证明出来,我会试一试并奖励梦寐以求的复选框。 谢谢! –