2015-07-09 64 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。 。 。這是不需要的,因爲列有不同的名稱。不過,這是可取的。 –

相關問題