按sql中的动态范围分组(cockroachdb/postgres)

unftdfkk  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(440)

我有个问题

select s.session_id, array_agg(sp.value::int8 order by sp.value::int8) as timestamps
from sessions s join session_properties sp on sp.session_id = s.session_id
where s.user_id = '6f129b1c-43a6-4871-86f6-1749bfe1a5af' and sp.key in ('SleepTime', 'WakeupTime') and value != 'None' and value::int8 > 0 
group by s.session_id

结果看起来像

f321c813-7927-47aa-88c3-b3250af34afa    | {1588499070,1588504354}
f38a8841-c402-433d-939d-194eca993bb6    | {1588187599,1588212803}
2befefaf-3b31-46c9-8416-263fa7b9309d    | {1589912247,1589935771}
3da64787-65cd-4305-b1ac-1393e2fb11a9    | {1589741569,1589768453}
537e69aa-c39d-484d-9108-2f2cd956d4ee    | {1588100398,1588129026}
5a9470ff-f930-491f-a57d-8c089e535d53    | {1589140368,1589165092}

第一列是唯一的id,第二列是 from 以及 to 时间戳。
现在我有了第三个表,其中有一些timeseries数据

records
------------------------
timestamp | name | value

有没有可能找到 avg(value) 从上的会话ID组中的记录 from 以及 to 时间戳。
我可以在应用程序中运行for循环,并执行联合以获得所需的结果。但我想知道这在中国是否可行 postgres 或者 cockroachdb

uqdfh47h

uqdfh47h1#

我不会聚合这两个值,而是使用两个连接来查找它们。这样就可以确定哪个值属于哪个属性。
一旦有了这个结果,就可以将这个结果连接到records表中。

with ranges as (
  select s.session_id, st.value as from_value, wt.value as to_value
  from sessions s 
    join session_properties st on sp.session_id = s.session_id and st.key = 'SleepTime'
    join session_properties wt on wt.session_id = s.session_id and wt.key = 'WakeupTime'
  where s.user_id = '6f129b1c-43a6-4871-86f6-1749bfe1a5af' 
    and st.value != 'None' and wt.value::int8 > 0 
    and wt.value != 'None' and wt.value::int8 > 0 
)
select ra.session_id, avg(rc.value)
from records rc
  join ranges ra 
    on ra.from_value >= rc.timewstamp
   and rc.timestamp < ra.to_value
group by ra.session_id;

相关问题