mysql中的相关查询

mysql中的相关查询,mysql,sql,correlation,Mysql,Sql,Correlation,我还看到了计算两列之间相关性的方法。IMy问题和那个问题不同,因为我的查询更复杂,因为它不在列之间。我想找到查询中两个不同条件之间的相关性 我有一个表,其中有数据的搜索查询历史的网站。我想计算不同日期搜索的相关性。为了计算搜索查询的数量,我实现了以下功能: select to_date(time), query, platform, count(query) as search_no from search where `_month` = 2 and time between '2021-02

我还看到了计算两列之间相关性的方法。IMy问题和那个问题不同,因为我的查询更复杂,因为它不在列之间。我想找到查询中两个不同条件之间的相关性

我有一个表,其中有数据的搜索查询历史的网站。我想计算不同日期搜索的相关性。为了计算搜索查询的数量,我实现了以下功能:

select to_date(time), query, platform, count(query) as search_no
from search
where `_month` = 2 and time between '2021-02-05 00:00:00' and '2021-02-05 23:59:59' and platform = 'application'
group by to_date(time), query, platform
order by search_no desc limit 1000
它工作得很好。它将搜索次数计算为2021-02-05的搜索编号。我想找到的是两个不同日期之间的相关性,比如2021-02-05和2021-01-29

相关公式如下:

PS:x是2021-02-05第一天的数据,y是2021-01-29第二天的数据

我试过的


我不知道如何实现它。

如果我理解正确,您需要两天总结的相关性。这将从以下数据开始:

   select query,
         sum(date(time) = '2021-02-05') as x,
         sum(date(time) = '2021-02-06') as y,
         count(*) as cnt
  from search
  where `_month` = 2 and
         time >= '2021-02-05' and
         time < '2021-02-07' and
         platform = 'application'
  group by query;
然后,您可以将其直接插入公式:

with dataset as (
       select query,
             sum(date(time) = '2021-02-05') as x,
             sum(date(time) = '2021-02-06') as y,
             count(*) as cnt
      from search
      where `_month` = 2 and
             time >= '2021-02-05' and
             time < '2021-02-07' and
             platform = 'application'
      group by query
     )
select (sum( (x - avg_x) * (y - avg_y) ) /
        sqrt(nullif( sum(power(x - avg_x, 2) * power(y - avg_y, 2)), 0))
       ) as pearson_correlation
from (select d.*,
             avg(x) over () as avg_x,
             avg(y) over () as avg_y
      from dataset d
     ) d;

显然,您需要调整where子句中的日期范围,以适应您想要的任何一天。我认为没有理由使用limit,这将通过填充查询来实现。

如果您只是将数据显示为一个示例表,那将更有帮助。完全不清楚数据中的x是什么,因为聚合列都不是数字。你确定你不知道什么是卡方检验吗?@GordonLinoff当然,我会在3分钟后加上它。谢谢你的评论。是的,我只想计算相关性。我添加了我自己的查询。请你看一下好吗?我也试过你的,但不起作用,因为我认为sumdatetime不好,不应该是一个间隔。
with dataset as (
       select query,
             sum(date(time) = '2021-02-05') as x,
             sum(date(time) = '2021-02-06') as y,
             count(*) as cnt
      from search
      where `_month` = 2 and
             time >= '2021-02-05' and
             time < '2021-02-07' and
             platform = 'application'
      group by query
     )
select (sum( (x - avg_x) * (y - avg_y) ) /
        sqrt(nullif( sum(power(x - avg_x, 2) * power(y - avg_y, 2)), 0))
       ) as pearson_correlation
from (select d.*,
             avg(x) over () as avg_x,
             avg(y) over () as avg_y
      from dataset d
     ) d;