2017-02-17 6 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週目は過去7日間です。過去の週までの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 

aggregate filter syntaxを使用:

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

lateralは9.3です。以前のバージョンでは、式weekをフィルタ条件に移動しました。

+0

ありがとうございます - 私はもっと集計フィルタsynatxに掘り下げます。エラー:演算子が存在しない:日付/整数 行12:(current_date - lf.created_at :: date/7を週として選択)... ^ ヒント:演算子は一致しません指定された名前と引数の型明示的な型キャストを追加する必要があるかもしれません。 –

+0

@LancePoole固定 –

+0

- 質問についての質問。チームテーブルには、このクエリに表示されない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句

  • ORDERは無意味でした。
  • 最も内側の副問い合わせのcreated_atは使用されませんでした。
  • wk_offsetテストはWHERE句で移動され、2つの異なるステップでは実行されません。
  • 最も外側のサブクエリは必要ありませんでした。 9.4+バージョンで
+0

Fabian - 私は毎週このクエリを何回もやりますか? –

関連する問題