views:

50

answers:

0

I have 2 tables - sentiment & comments - that I'm trying to join averages and counts from based on a set of derived time ranges in mysql.

Here's what I have that works individually:

  SELECT ROUND(AVG(sentiment.sent_value)) AS sentiment,
         ROUND( FLOOR( (sentiment.sent_video_time) /5000 ) *5000 ) AS start_time, ' - ', 
         ROUND( (FLOOR( (sentiment.sent_video_time) /5000 ) +1 ) *5000) AS end_time
    FROM sentiment
GROUP BY end_time

...and...

  SELECT COUNT(comment.commID) AS comments,
         ROUND( FLOOR( (comment.c_video_time) /5000 ) *5000 ) AS ctime, ' - ', 
         ROUND( (FLOOR( (comment.c_video_time) /5000 ) +1 ) *5000) AS cend_time
    FROM comment
GROUP BY ctime

The time increments will always match up. There will always be sentiment values for each time increment, but not always comments.

I'm trying to get a combined table to output:

sentiment,  comments,    start_time - end_time
-----------------------------------------------
65,         8,           0 - 5000
42,         0,           5000 - 10000
35,         17,          10000 - 15000

Thanks!

UPDATE:

Thanks to the below answer, I've gotten a little further. This returns correct data, but if there are not comments for a corresponding sentiment time segment, it's excluding those rows. I'd like for it to show "0" for comments in that section.

I know it's because the way I've define "GROUP BY" but I can't firgure out the correct condition to handle when there are 0 comments to 1+ sentiment for a given blick of time.

SELECT x.sentiment AS senti,
       y.comments AS comments,
       x.start_time AS time
 FROM (SELECT campaign_campID,
              ROUND(AVG(sentiment.sent_value)) AS sentiment,
              ROUND( FLOOR( (sentiment.sent_video_time) /5000 ) *5000 ) AS start_time, ' - ', 
              ROUND( (FLOOR( (sentiment.sent_video_time) /5000 ) +1 ) *5000) AS end_time
         FROM sentiment
     GROUP BY start_time, campaign_campID) x
 JOIN (SELECT campaign_campID,
              CASE 
                WHEN COUNT(comment.commID) =  NULL THEN 0 
                ELSE COUNT(comment.commID) 
              END AS comments,
              ROUND( FLOOR( (comment.c_video_time) /5000 ) *5000 ) AS cstart_time, ' - ', 
              ROUND( (FLOOR( (comment.c_video_time) /5000 ) +1 ) *5000) AS cend_time
         FROM comment
     GROUP BY cstart_time, campaign_campID) y ON y.campaign_campid = x.campaign_campid
WHERE y.cstart_time = x.start_time
GROUP BY x.start_time

Here are the tables:

CREATE TABLE comment ( 
    commID INT NOT NULL AUTO_INCREMENT , 
    campaign_campID INT NULL DEFAULT NULL , 
    c_video_time BIGINT(20) NULL 
) 

CREATE TABLE sentiment ( 
    campaign_campID INT NULL , 
    sent_value TINYINT NULL , 
    sent_video_time BIGINT(20) NULL 
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci