2015-07-09 66 views
0

鉴于我有2个表,我如何看到有多少不同的X值是在Y的不同值,但是在31天(或一个月)之前date_X?mysql计数字段值出现在另一个表字段中的次数

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是不同的(Y)的数量相匹配不同(X)为31天给出date_period之前

count_y是在给定的date_period之前长达31天的不同(Y)。

percent_match只是num_match/count_y

这个问题的扩展,我刚才的问题在这里:你这是对过期的非等值连接 join mysql on a date range

回答

0

的一种方式。然后,你可以指望ÿ无论是在该组或匹配的不同的值:

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线为不同。我误读了期望的结果,因此我认为适当的查询是:

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; 
+0

您是否需要第9行的y.date_y – jxn

+0

@jxn。 。 。这是不需要的,因为列有不同的名称。不过,这是可取的。 –

相关问题