tmp_year_channel_avg_ratings_stat_by_tv.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. """电视台近一年平均收视率
  4. 计算方法:取出电视台的一年收视数据,求平均数
  5. avg(audience_rating) group by channel, theater_attribute
  6. province_input: odl.ad_television
  7. province_output: tmp.channel_avg_ratings
  8. area_input: odl.area_ad_television
  9. area_output: odl.area_channel_avg_ratings
  10. """
  11. import sys
  12. from fty_util.common import Mysql, Util
  13. reload(sys)
  14. sys.setdefaultencoding('utf8')
  15. class channel_avg_ratings():
  16. # 央卫视频道
  17. def province(self):
  18. conn = Mysql.createOfflineConn()
  19. first_day = Util.get_first_date_of_yesterday()
  20. one_year_ago = Util.get_max_date_of_one_year_ago(first_day)
  21. # 计算最近一年电视台的平均收视率
  22. station_dict = {}
  23. sql = """
  24. select channel, theater_attribute, avg(audience_rating) as avg_rate from odl.ad_television
  25. where tv_date > '%s' and tv_date <= '%s'
  26. group by channel, theater_attribute
  27. """
  28. sql = sql % (one_year_ago, first_day)
  29. rows = Mysql.getAll(sql, conn=conn)
  30. data_list = []
  31. sql = """
  32. insert into tmp.channel_avg_ratings (channel, theater_attribute, value) values (%s, %s, %s)
  33. """
  34. for row in rows:
  35. channel = row['channel']
  36. theater_attribute = row['theater_attribute']
  37. avg_rate = row['avg_rate']
  38. data_list.append((channel, theater_attribute, avg_rate))
  39. Mysql.insertMany(sql, data_list, conn)
  40. Mysql.close(conn)
  41. # 省级地面频道
  42. def area(self):
  43. conn = Mysql.createOfflineConn()
  44. first_day = Util.get_first_date_of_yesterday()
  45. one_year_ago = Util.get_max_date_of_one_year_ago(first_day)
  46. # 计算最近一年电视台的平均收视率
  47. station_dict = {}
  48. sql = """
  49. select channel, theater_attribute, avg(audience_rating) as avg_rate from odl.area_ad_television
  50. where tv_date > '%s' and tv_date <= '%s'
  51. group by channel, theater_attribute
  52. """
  53. sql = sql % (one_year_ago, first_day)
  54. rows = Mysql.getAll(sql, conn=conn)
  55. data_list = []
  56. sql = """
  57. insert into tmp.area_channel_avg_ratings (channel, theater_attribute, value) values (%s, %s, %s)
  58. """
  59. for row in rows:
  60. channel = row['channel']
  61. theater_attribute = row['theater_attribute']
  62. avg_rate = row['avg_rate']
  63. data_list.append((channel, theater_attribute, avg_rate))
  64. Mysql.insertMany(sql, data_list, conn)
  65. Mysql.close(conn)
  66. if __name__ == '__main__':
  67. if len(sys.argv) != 2:
  68. print '没有输入参数,退出'
  69. sys.exit(0)
  70. print 'method name is ' + sys.argv[1]
  71. obj = channel_avg_ratings()
  72. try:
  73. getattr(obj, sys.argv[1])()
  74. except Exception, e:
  75. print e