2015-07-12 60 views
0

我想計算pid_raw總數中(pid = pid_raw)的百分比,其中date_raw是日期前31天。mysql讓子查詢脫離加入

我知道我可以做一部分內部連接,但因爲我想獲得百分比,因此需要pid_raw的總數而不管匹配,這個子查詢不能成爲內部連接的一部分。我如何編寫我的子查詢來獲得不受內聯接影響但符合where子句的pid_raw的總數?

table1 
date   pid 
2015-06-01 223 
2015-06-01 333 
2015-05-01 124 
2015-05-01 543 


table2 
date_raw  pid_raw 
2015-05-30 223 
2015-05-15 111 
2015-05-03 333 
2015-05-02 242 
2015-05-05 300 
2015-04-10 124 
2015-04-15 543 
2015-04-09 511 


Example output 
date   pid_percentage 
2015-06-01  0.40   <-------(2/5) 
2015-05-01  0.67   <------(2/3) 

我須藤代碼:

select count(a.pid)/(select count(b.pid_raw) from b) AS pid_percentage, a.date  from 
table1 a join table2 b 
ON a.pid = b.pid_raw 
Where a.date - b.date_raw <=31 and a.date - b.date_raw > 0 
group by a.date 
order by YEAR(a.date),Month(a.date); 

回答

0

我的建議是加入的日期,然後使用條件聚集的計算:

select t1.date, 
     count(distinct case when t1.pid = t2.pid_raw then t1.pid end) as NumMatches, 
     (count(distinct case when t1.pid = t2.pid_raw then t1.pid end)/
     count(distinct case when t1.pid = t2.pid_raw then t2.pid_raw end) 
     ) as percentage_pid 
from table1 t1 left join 
    table2 t2 
    on t2.date_raw between t1.date - interval 31 day and t1.date 
group by t1.date; 
+0

感謝儘管這種運行時,它的時間太長並在我得到任何輸出之前超時。有沒有更好的方法來做到這一點? – jxn