Postgres - 如何检查结果表中是否不存在日期,如果存在则将数据设置为零

问题描述 投票:0回答:1

我有一个查询,告诉我每个客户每月分配了多少设备。

但是我没有未分配设备的月份的条目:

enter image description here

我需要像这样添加这些行:

clientId | date         | assigned
11       | 2024-02-01   | 3
11       | 2024-03-01   | 0
11       | 2024-04-01   | 0
11       | 2024-05-01   | 0
11       | 2024-06-01   | 163

这是我的询问:

select "clientId", date_trunc('month', "tsAssignation"), count("deviceId") as assigned
from "devicesAssignations"
group by "clientId", date_trunc('month', "tsAssignation")

有办法做到这一点吗?

database postgresql
1个回答
0
投票

就是这里。首先列出所有用户 ID 和所有月份,然后将其添加到您的表格中。

select t.client_id, s::date "Date", coalesce(assigned, 0) assigned
from 
 (
  (select distinct client_id from the_table) cross join 
  generate_series('2024-01-01', '2024-12-01', interval '1 month') as s
 ) as t 
left join the_table 
     on assigned_date = t.s and t.client_id = the_table.client_id
order by t.client_id, "Date";

DB-fiddle 演示

© www.soinside.com 2019 - 2024. All rights reserved.