2017-09-02 81 views
1

使用PostgreSQL,版本9.5.8累計總按周 - PostgreSQL的

下面我有一個工作查詢,這給了我所有賬戶的準備賬戶的PCT。然後這個表格按周分割,給我這個星期創建的賬戶數量,隨後準備就緒。下面

查詢:

SELECT 
       date_trunc('week', al.created_at) as week_created, 
       count(case when ra.status='ready' then 1 end) as total_accounts, 
       count(case when ra.status='ready' AND ra.tests > 0 then 1 end) as accounts_ready, 
       concat(round(count(case when ra.status='ready' AND ra.tests > 0 then 1 end) :: decimal /count(case when ra.status='ready' then 1 end) :: decimal * 100.0), '%') as pct_accounts_ready 

    FROM "ready_accounts" ra 
    JOIN "accounts_list" al 
    ON al.id=ra.id 
    GROUP BY week_created 
    ORDER BY week_created DESC; 

結果集看起來像這樣:

周創---------總帳戶----帳戶準備--- - Pct帳戶準備就緒

Monday 14 Aug ---- 50 ----------------39 ---------------- 78% 
Monday 7 Aug ---- 20 ----------------10 ---------------- 20% 

問題是,我得到的結果不是累積的,他們只是爲了一週,w對於我想要達到的目標來說,這是毫無意義的。

我想一個結果集,它表明代替:

Monday 14 Aug --- 70 ------------------- 49 ---------------- 70% 
Monday 7 Aug --- 20 ------------------- 10 ---------------- 20% 

取樣輸入數據:

的樣本數據看起來像這樣: 準備賬表:

ra.id ra.status ra.tests 
123  ready  1 
124  not_ready 2 
125  not_ready 0 
126  ready  1 
127  ready  0 
128  ready  0 
129  ready  1 

賬戶列表表格:

al.id al.created_at 

123  Monday 14 August 
124  Monday 7 August 
125  Monday 14 August 
126  Monday 14 August 
127  Monday 7 August 
128  Monday 14 August 
129  Monday 31 July 

我已經嘗試了很多解決方案,但都陷入困境。任何解決方案的例子都會很有幫助!

預先感謝您。 我對此很新,所以任何解釋都會很有用!

+0

沒有看到您的輸入數據,可能很難調試您的查詢。你能爲你的問題提供一個最小和可重複的樣本嗎? –

+0

否。刪除上述評論並將該數據放入您的問題中。 –

+0

完成 - @TimBiegeleisen – ElNuni

回答

1

使用沒有派生表中的最後一列(FROM子句中的子查詢)的查詢並將sum()用作窗口函數。計算外包裝查詢中的百分比:

select 
    week_created, 
    total_accounts, 
    accounts_ready, 
    concat((accounts_ready/ total_accounts* 100)::int, '%') as pct_accounts_ready 
from (
    select 
     week_created, 
     sum(total_accounts) over w as total_accounts, 
     sum(accounts_ready) over w as accounts_ready 
    from (
     select 
      date_trunc('week', al.created_at) as week_created, 
      count(case when ra.status='ready' then 1 end) as total_accounts, 
      count(case when ra.status='ready' and ra.tests > 0 then 1 end) as accounts_ready 
     from "ready_accounts" ra 
     join "accounts_list" al 
     on al.id=ra.id 
     group by week_created 
     ) s 
    window w as (order by week_created) 
    ) s 
order by week_created desc; 
+0

謝謝。 我不認爲這是工作,因爲關係'week_created'來自另一個表,我已經加入子查詢中的表。 如果你看看我原來的查詢,我通過加入另一個表('accounts_list')到'ready_accounts'表獲得week_created。我想我需要保持最後一個子查詢中的連接? – ElNuni

+0

當然可以。查看更新後的答案。 – klin

+0

不錯 - 這真棒,給了我想要的結果。非常感謝你!! – ElNuni