2016-12-14 168 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%的字段。 一旦我證明出來,我會試一試並獎勵夢寐以求的複選框。 謝謝! –