我有2张桌子 - 情绪&评论 - 我正在尝试根据mysql中的一组派生时间范围加入平均值和计数。
这就是我个人的作品:
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
...和...
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
时间增量始终匹配。每个时间增量总会有情绪值,但并不总是评论。
我正在尝试将组合表输出:
sentiment, comments, start_time - end_time
-----------------------------------------------
65, 8, 0 - 5000
42, 0, 5000 - 10000
35, 17, 10000 - 15000
谢谢!
由于以下答案,我已经进一步了解。这会返回正确的数据,但如果没有相应情绪时间段的注释,则会排除这些行。我希望它在该部分的评论中显示“0”。
我知道这是因为我定义“GROUP BY”的方式,但是如果在给定的时间内对0+评论有0评论,我就无法确定处理的正确条件。
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
以下是表格:
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
答案 0 :(得分:1)
左表连接表评论与表情绪。 在内部查询中使用Coalesce而不是case 如果表情绪有0行,则y.comments = NULL,因此coalesce(NULL,0)将返回0
SELECT x.sentiment AS senti,
COALESCE(y.comments,0) 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
LEFT JOIN (SELECT campaign_campID, COUNT(comment.commID) 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 x.campaign_campid = y.campaign_campid AND x.start_time = y.cstart_time