0
根據reference link我習慣於在一年內使用單個表進行計數。但在這裏,我需要根據用戶類型和財產關係計算兩張關係表。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:如果將用戶登錄類型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月當月用計數也加入語句後的狀態。但在年內沒有獲得其他月份。
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月當月只有結果。但我需要在這裏剩下的幾個月的計數爲零 –
更新問題與一些示例數據?.. –
示例數據更新與問題。等待你的回答這個 –