Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 按日期分组的嵌套Select查询_Mysql_Join_Group By_Nested Queries - Fatal编程技术网

Mysql 按日期分组的嵌套Select查询

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%

我有一个名为“rawTweets”的表,如下所示

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