Mysql 按日期分组的嵌套Select查询
我有一个名为“rawTweets”的表,如下所示Mysql 按日期分组的嵌套Select查询,mysql,join,group-by,nested-queries,Mysql,Join,Group By,Nested Queries,我有一个名为“rawTweets”的表,如下所示 tweet, date, id, username, compoundScore 我想计算某些关键字的平均值,并按日期对结果进行分组,但我还是有点像sql“新手”。在我的脑海里,它看起来像下面这样 需要一点指导-谢谢 SELECT `date`, AVG( SELECT compoundScore FROM rawTweets WHERE tweet LIKE '%trump%
tweet, date, id, username, compoundScore
我想计算某些关键字的平均值,并按日期对结果进行分组,但我还是有点像sql“新手”。在我的脑海里,它看起来像下面这样
需要一点指导-谢谢
SELECT
`date`,
AVG(
SELECT compoundScore
FROM rawTweets
WHERE tweet LIKE '%trump%'
) AS Trump,
AVG(
SELECT compoundScore
FROM rawTweets
WHERE tweet LIKE '%chaffetz%'
) as Chaffetz
FROM rawTweets
WHERE
compoundScore <> 0.0
AND compoundScore IS NOT NULL
GROUP BY `date`;
您可以尝试以下方法,而不是使用嵌套选择:
SELECT
`date`,
AVG(COALESCE(rt2.compoundScore, 0)) AS Trump,
AVG(COALESCE(rt3.compoundScore, 0)) AS Chaffetz
FROM
rawTweets rt
-- Trump
LEFT JOIN rawTweets rt2 ON
rt2.id = rt.id
AND rt2.tweet LIKE '%trump%'
-- Chaffetz
LEFT JOIN rawTweets rt3 ON
rt3.id = rt.id
AND rt3.tweet LIKE '%chaffetz%'
WHERE
compoundScore <> 0.0
AND compoundScore IS NOT NULL
GROUP BY `date`;
执行此操作时,您可以使用avg和case:
select date
,avg(case when tweet like '%trump%' then compoundScore else null end) as Trump
,avg(case when tweet like '%chaffetz%' then compoundScore else null end) as Chaffetz
from rawTweets
where compoundScore <> 0.0 and compoundScore is not null
group by date