mysql 计算一个字段值在另一个 table 字段中出现的次数

mysql count number of times a field value appear in another table field

鉴于我有 2 个表,我如何才能看到有多少不同的 X 值在不同的 Y 值中但在 date_X 之前的 31 天(或一个月)内?

tb1
     date_X        X
    2015-05-01    cat
    2015-05-01    pig
    2015-05-01    mouse
    2015-04-01    dog
    2015-04-01    horse
tb2  
    date_Y         Y
    2015-04-30    cat
    2015-04-02    cat
    2015-04-05    mouse
    2015-04-15    rabbit
    2015-04-10    pig
    2015-03-20    dog
    2015-03-10    horse
    2015-03-09    frog

比如我要:

date_period num_match count_y percent_match
2015-05-01   2            4        40
2014-04-01   2            3        67

date_period 是独一无二的(date_x)

num_match 是在给定 date_period

之前最多 31 天与不同 (X) 匹配的不同 (Y) 的数量

count_y 是给定 date_period.

之前长达 31 天的不同 (Y)

percent_match 就是 num_match/count_y

这个问题是我之前在这里提出的问题的延伸:

一种方法是在日期上使用非等值连接。然后您可以计算集合或匹配项中 y 的不同值:

select x.date_x,
       count(distinct case when x.x = y.y then y.seqnum end) as nummatch,
       count(distinct y.seqnum) as count_y,
       (count(distinct case when x.x = y.y then y.seqnum end) /
        count(distinct y.seqnum) 
       ) as ratio
from x left join
     (select y.*, rownum as seqnum
      from y
     ) y
     on y.date_y between x.date_x - 31 and x.date_x
group by x.date_x;

编辑:

以上将 y 中的两行 "cat" 视为不同。我误读了想要的结果,所以我认为合适的查询是:

select x.date_x,
       count(distinct case when x.x = y.y then y.y end) as nummatch,
       count(distinct y.y) as count_y,
       (count(distinct case when x.x = y.y then y.y end) /
        count(distinct y.y) 
       ) as ratio
from x left join
     y
     on y.date_y between x.date_x - 31 and x.date_x
group by x.date_x;