在Mysql中计算

时间:2011-11-16 15:30:00

标签: python 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中做到这一点?

1 个答案:

答案 0 :(得分: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