2017-02-16 4 views
0

J'ai une table appelée « rawTweets » qui se présente comme suitNested requêtes Select Groupé par date

tweet, date, id, username, compoundScore 

Je veux calculer les moyennes pour certains mots-clés et grouper les résultats par date, mais je suis un peu coincé (encore très un sql 'newb'). Dans ma tête, ça ressemble à quelque chose comme ça.

Pourrait utiliser un peu d'orientation - merci!

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`; 

Répondre

0

Au lieu d'utiliser la nested select que vous faites, vous pouvez essayer un compagnon:

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`; 
0

Vous pouvez utiliser avg et case when pour ce faire:

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