Sql查询以查找两个给定日期之间的视图百分比差异

时间:2011-11-14 22:45:16

标签: php mysql compare

我正在尝试编写一个SQL查询,但我发现一些困难。我想要的是:

假设我们有一个表格,用于存储每天观看视频的时间。 例如:

  • day:14/11/2011,video_id:3539,timeswatched:125
  • and:15/11/2011,video_id:3539,timeswatched:162

(所以表存储video_id,day,timeswatched)

我想要的是制作一个广告牌/图表类型,显示日期之间(今天和昨天)8个观看(今天)视频的时间百分比变化。 (请注意,视频可能在今天或昨天都没有被观看过 - 如果这是一个问题吗?)

所以结果应该是这样的:video-id:3539今天有+ 23%或-44%(或..)更多/更少的观点(我们需要知道如何找到23%)

谢谢!

3 个答案:

答案 0 :(得分:1)

Select Top8.idvideo, (vtoday.times - vyesterday.times) / vtoday.times
From 
  (select 
     Idvideo from Nviews 
     Where day = Curdate()
   order by watches desc limit 8) top8 
  Inner join
   NViews vtoday 
       on vtoday.day = curdate()
       and vtoday.idvideo=top8.idvideo
  Left outer join
    NViews vyesterday
       On vyesterday.day= Date_add( curdate(), interval -1 day) and
           Vyesterday.idvideo = top8.idvideo

答案 1 :(得分:0)

SELECT
    videoWatchCountToday.timeswatched AS timeswatchedtoday,
    videoWatchCountYesterday.timeswatched AS timeswatchedyesterday,
    CASE
        WHEN COALESCE(videoWatchCountYesterday.timeswatched, 0) = 0 THEN NULL
        ELSE ROUND(100 * (videoWatchCountToday - videoWatchCountYesterday) / videoWatchCountYesterday, 0)
    END AS change
FROM
    videoWatchCount AS videoWatchCountToday
    LEFT JOIN videoWatchCount AS videoWatchCountYesterday ON
        videoWatchCountToday.video_id = videoWatchCountYesterday.video_id AND
        videoWatchCountYesterday.day = '2011-11-14'
WHERE
    videoWatchCountToday.video_id = 3539 AND
    videoWatchCountToday.day = '2011-11-15'

答案 2 :(得分:0)

我会做(伪代码):

yesterday = sql('SELECT timeswatched  FROM videos WHERE DATE(date_field) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)')
today = sql('SELECT timeswatched  FROM videos WHERE DATE(date_field) = CURRENT_DATE()')

if (today == 0 || yesterday == 0)
  // Special handling... 0 -> 10 views is an infinite increase.
else
  return (100 * yesterday / today) - 100;