mysql计数字段值在另一个表字段中出现的次数
假设我有两个表,我怎么能看到有多少不同的X值在不同的Y值中,但在日期X之前的31天(或一个月)内mysql计数字段值在另一个表字段中出现的次数,mysql,sql,join,subquery,Mysql,Sql,Join,Subquery,假设我有两个表,我怎么能看到有多少不同的X值在不同的Y值中,但在日期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-0
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\u period
是唯一的(date\u x)
num\u match
是在给定日期之前31天内与distinct(X)匹配的distinct(Y)数
count_y
是给定日期前31天内的不同(y)
percent\u match
只是num\u match
/count\u 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;
你需要你的在线日期吗9@jxn . . . 不需要它,因为列具有不同的名称。不过,这是可取的。