Presto - 如何在一个查询中的所有列之间执行关联

Presto - how to perform correlations on between all columns in one query

我有一个 table 格式如下:

A   B   C   D 
7   7   2   12
2   2   3   4
2   2   2   4
2   2   2   3
5   5   2   7

我想使用内置相关函数计算每一列之间的相关性 (https://prestodb.io/docs/current/functions/aggregate.html corr(y, x) → double)

我可以 运行 遍历所有列并每次执行 corr 计算: select corr(A,B) from table 但我想减少访问 presto 的次数,如果可能的话,运行 在一次查询中访问它。

是否有可能得到通过某个阈值的列名或者至少是一个查询中所有可能组合之间的相关分数?

谢谢。

I would like to calculate correlations between each of the columns

相关性涉及两个数据系列(在 SQL 中,两列)。因此,我将您的问题理解为:如何计算 table 中每个可能的列组合的相关性。看起来像:

select
    corr(a, b) corr_a_b,
    corr(a, c) corr_a_c,
    corr(a, d) corr_a_d,
    corr(b, c) corr_b_c,
    corr(b, d) corr_c_d,
    corr(c, d) corr_c_d
from mytable

您可以使用横向连接来取消透视 table,然后使用自连接和聚合:

with v as (
      select v.*, t.id
      from (select t.*,
                   row_number() over (order by a) as id
            from t
           ) t cross join lateral
           (values ('a', a), ('b', b), ('c', c), ('d', d)
           ) v(col, val)
     )
select v1.col, v2.col, corr(v1.val, v2.val)
from v v1 join
     v v2
     on v1.id = v2.id and v1.which < v2.which
group by v1.col, v2.col;

row_number()只是为每一行生成一个唯一的id,用于自连接。您可能已经有包含此信息的专栏,因此可能没有必要。