假设,为了简单起见,我有下表:
id amount p_id date
------------------------------------------------
1 5 1 2020-01-01T01:00:00
2 10 1 2020-01-01T01:10:00
3 15 2 2020-01-01T01:20:00
4 10 3 2020-01-01T03:30:00
5 10 4 2020-01-01T03:50:00
6 20 1 2020-01-01T03:40:00下面是我想要的示例响应:
{
"2020-01-01T01:00:00": 25, -- this is from adding records with ids: 2 and 3
"2020-01-01T03:00:00": 55 -- this is from adding records with ids: 3,4,5 and 6
}我想要获得所有按小时分组的唯一p_id的总数(sum(amount))。
每个p_id选择的行是具有最新date的那一行。因此,例如,上面响应中的第一个值不包括id 1,因为带有id 2的记录具有相同的p_id,而该行上的date晚一些。
一个棘手的事情是,我想包括每个p_id的所有amount的总和,如果他们的date是在呈现的小时之前。例如,在响应的第二个值(关键字为"2020-01-01T03:00:00")中,尽管id 3在不同的小时有时间戳,但它是该p_id 2的最新时间戳,因此包含在"2020-01-01T03:00:00“的和中。但是包含id 6的行用相同的p_id 1覆盖了id 2。
换句话说:始终获取到目前为止每个p_id的最新amount,并计算表中找到的每个不同小时的和。
发布于 2020-07-06 07:08:32
创建一个包含row_number() over (partition by p_id, date_trunc('hour',"date") order by "date" desc) as pid_hr_seq的CTE,然后使用where pid_hr_seq = 1编写针对该CTE的查询。
https://stackoverflow.com/questions/62746887
复制相似问题