以DB / 2计算总和,平均值和90%

时间:2016-12-14 21:03:58

标签: sql db2

如果我有下表stats

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%avg()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,{{1 },average duration of the fastest 90%

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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")