2017-02-17 25 views
0
select id, wk0_count 
from teams 
left join 
    (select team_id, count(team_id) as wk0_count 
    from (
     select created_at, team_id, trunc(EXTRACT(EPOCH FROM age(CURRENT_TIMESTAMP,created_at))/604800) as wk_offset 
     from loan_files 
     where loan_type <> 2 
     order by created_at DESC) as t1 
    where wk_offset = 0 
    group by team_id) as t_wk0 
on teams.id = t_wk0.team_id 

我已經創建了上面的查詢,顯示了每個團隊在給定的一週內做了多少貸款。第0周是過去七天。Postgresql過去數星期

理想情況下,我需要一張表格,顯示每個團隊在過去8周內按每週分組的數量。輸出將如下所示:

enter image description here

任何想法上做到這一點的最好方法是什麼?

+0

Mysql或postgresql? – GurV

+0

@GurV看起來像Postgres給我 –

回答

0
select 
    t.id, 
    count(week = 0 or null) as wk0, 
    count(week = 1 or null) as wk1, 
    count(week = 2 or null) as wk2, 
    count(week = 3 or null) as wk3 
from 
    teams t 
    left join 
    loan_files lf on lf.team_id = t.id and loan_type <> 2 
    cross join lateral 
    (select (current_date - created_at::date)/7 as week) w 
group by 1 

在9.4+版本使用aggregate filter syntax

count(*) filter (where week = 0) as wk0, 

lateral爲9.3。在之前的版本中,將week表達式移至篩選條件。

+0

謝謝 - 我會更多地研究聚合過濾器synatx。也許這就是我得到這個錯誤的原因:錯誤:操作符不存在:日期/整數 行12:(選擇current_date - lf.created_at :: date/7 as as week)... ^ 提示:沒有操作符匹配給定的名稱和參數類型。您可能需要添加顯式類型轉換。 –

+0

@LancePoole固定 –

+0

- 關於查詢的問題。在team表中有沒有出現在這個查詢中的teams.id。這是爲什麼?我嘗試了一個左連接,但這不起作用。理想情況下,結果會列出來自團隊的每個teams.id。 –

0

下面的查詢如何?

SELECT team_id AS id, count(team_id) AS wk0_count 
FROM teams LEFT JOIN loan_files ON teams.id = team_id 
WHERE loan_type <> 2 
    AND trunc(EXTRACT(epoch FROM age(CURRENT_TIMESTAMP, created_at))/604800) = 0 
GROUP BY team_id 

值得注意的變化是:

  • ORDER BY在子查詢條款是沒有意義的;
  • 最內層子查詢中的created_at從未使用;
  • wk_offset測試在WHERE子句中移動,而不是在兩個不同的步驟中完成;
  • 最外面的子查詢是不需要的。
+0

Fabian - 我會在輸出中每次想要多次查詢這個查詢,然後加入這些查詢? –

相關問題