0
としてreference link 1年以内の月に基づいてカウントを取得するのに使用されます。しかし、ここで私は、ユーザーの種類と不動産に基づいて関係を持つ2つのテーブルを持つカウントを取得する必要があります。Postgresqlのクエリで、複数のテーブルを使用して年内の月数を取得する
サンプル・データ
住民テーブル
resident_id | resident_user_id | resident_estate_id | created_at |
31 | 75 | 1 | 2016-12-07 11:22:23 |
32 | 76 | 16 | 2016-12-07 11:22:23 |
37 | 81 | 16 | 2016-12-07 11:22:23 |
38 | 84 | 17 | 2016-12-07 11:22:23 |
ユーザー表
ここでは、条件に基づいてする必要があり、1年以内のデータを一覧表示します。下の例のクエリは、データを取得するために使用されました。
例1:ユーザーログインタイプ3を2に変更した場合、12月のカウントは1になりますが、ゼロカウントを取得する必要があります。
SELECT to_char(i, 'YYYY') as year_data, to_char(i, 'MM') as month_data, to_char(i, 'Month') as month_string, count(resident_id) as ios_total_count
FROM generate_series(now() - INTERVAL '1 year', now(), '1 month') as i
left join residents on (to_char(i, 'YYYY') = to_char(created_at, 'YYYY') and to_char(i, 'MM') = to_char(created_at, 'MM') and resident_estate_id = 17)
left join users on (users.id=residents.resident_user_id and users.user_login_type = 3)
GROUP BY 1,2,3 order by year_data desc, month_data desc
limit 12
出力
"2016";"12";"December ";1 "2016";"11";"November ";0 "2016";"10";"October ";0 "2016";"09";"September";0 "2016";"08";"August ";0 "2016";"07";"July ";0 "2016";"06";"June ";0 "2016";"05";"May ";0 "2016";"04";"April ";0 "2016";"03";"March ";0 "2016";"02";"February ";0 "2016";"01";"January ";0
例2:私が使用した場合はどこにもカウントは12月の月になっ参加ステートメント後の状態。しかし、1年以内に他の月を得ることはできません。
SELECT to_char(i, 'YYYY') as year_data, to_char(i, 'MM') as month_data, to_char(i, 'Month') as month_string, count(resident_id) as ios_total_count
FROM generate_series(now() - INTERVAL '1 year', now(), '1 month') as i
left join residents on (to_char(i, 'YYYY') = to_char(created_at, 'YYYY') and to_char(i, 'MM') = to_char(created_at, 'MM'))
left join users on (users.id=residents.resident_user_id)
where residents.resident_estate_id = 17 and users.user_login_type = 3
GROUP BY 1,2,3 order by year_data desc, month_data desc
limit 12
予想される出力
"2016";"12";"December ";0 "2016";"11";"November ";0 "2016";"10";"October ";0 "2016";"09";"September";0 "2016";"08";"August ";0 "2016";"07";"July ";0 "2016";"06";"June ";0 "2016";"05";"May ";0 "2016";"04";"April ";0 "2016";"03";"March ";0 "2016";"02";"February ";0 "2016";"01";"January ";0
、12月の月の取得結果のみ。しかし、ここで残りの数ヶ月は0にする必要があります –
サンプルデータで質問を更新しますか? –
サンプルデータは質問で更新されています。この回答を待っています –