2011-11-16 74 views
0

我使用的命令计算在MySQL

select video_info count(distinct src_ip) from videoinfo 
    group by video_info 
    order by count(distinct src_ip) DESC 

来获取数据的2列,第一列表示每个视频项目,第二列记录他们有多少次被下载的标识符。

我也想计算一下,例如,5%的视频下载了两次,10%的视频下载了10次,然后将百分比数字和下载时间记录到两个数组中。

Mysql是否支持这种计算?或者我需要切换到Python来做到这一点?如果是这样,如何在Python中做到这一点?

回答

2

在Python中你可以使用这个:

cur.execute("SELECT video_info, COUNT(distinct src_ip) " 
      "FROM videoinfo " 
      "GROUP BY video_info " 
      "ORDER BY COUNT(DISTINCT src_ip) DESC") 

counter = dict(cur) 
for n in xrange(1, max(counter.itervalues()) + 1): 
    perc = 100./sum(1 for nb in counter.itervalues() if nb == n)/len(counter) 
    if perc: 
     print '%.f%% videos have been downloaded %d times' % (perc, n) 

随着counter = {'a': 1, 'b': 1, 'c': 2, 'd': 1, 'e': 2, 'f': 3}这个打印:

50% videos have been downloaded 1 times 
33% videos have been downloaded 2 times 
17% videos have been downloaded 3 times