为了进行分析,我有两个表,一个包含静态数据(我们称之为profile
),另一个包含每个时间戳的记录用户数据(我们称之为dynamic
)。在dynamic
中,可能有许多状态,如下所示:
profile_id | timestamp | state
-------------------------------
uuid1 | 2023-12...| state1
uuid1 | 2023-12...| state2
uuid1 | 2023-12...| state2
uuid1 | 2023-12...| state3
uuid1 | 2023-12...| state3
uuid1 | 2023-12...| state4
uuid2 | 2023-12...| state3
uuid2 | 2023-12...| state4
...
字符串
状态可以被分组,对于这个例子,我们假设state 1和state 2形成组1,state 3和state 4形成组2。一个高效的查询会是什么样子,它提供了一个布尔值,哪些配置文件已经优先于哪个状态组?我在考虑一个带有group-by的连接,但似乎找不到正确的语法:
select profile.id, profile.some_other_column, sub.has_group1, sub.has_group2
left join (
select profile_id, exists_in_groupby(state1, state2) as has_group1,
exists_in_groupby(state3, state4) as has_group2
from dynamic
group by profile_id) sub
on sub.profile_id = profile.id
型exists_in_groupby
应该用什么?或者有没有更有效的方法?请注意,dynamic
可能非常大,我们遇到了超时问题(这就是我问的原因)。非常感谢!
编辑:当前,太慢的方法和效率低下的方法
select profile.id, profile.some_other_column,
case
when 'state1' in (select state from dynamic where profile_id = profile.id)
or 'state2' in (select state from dynamic where profile_id =
profile.id)
then 1
else 0
end as has_group1,
case when 'state3' in (select state from dynamic where profile_id = profile.id)
or 'state4' in (select state from dynamic where profile_id = profile.id)
then 1
else 0
end as has_group2
left join dynamic
on dynamic.profile_id = profile.id
group by profile.id
型
1条答案
按热度按时间o2rvlv0m1#
我会做下面这样的事情:
字符串
与你的输出唯一的区别是,它有
null
而不是0
,它也可以管理,如果它是一个问题,在grafana。