【发布时间】:2016-12-12 13:04:44
【问题描述】:
根据reference link,我习惯于使用单表根据一年内的月份进行计数。但在这里我需要根据用户类型和资产来获取两个表的计数。
样本数据
居民表
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 |
用户表
id | name | user_login_type | created_at |
80 | rest | 3 | 2016-12-01 15:11:08 |
81 | appu | 2 | 2016-12-02 12:51:08 |
84 | sankar | 2 | 2016-12-06 11:11:29 |
85 | test | 1 | 2016-12-06 15:06:57 |
这里我们需要根据情况,列出一年内的数据。下面的示例查询用于获取数据。
示例 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:如果我在 join 语句之后使用 where 条件,得到 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
【问题讨论】:
标签: sql database postgresql postgresql-9.5