【问题标题】:Nested Select Queries Grouped by Date按日期分组的嵌套选择查询
【发布时间】:2017-02-16 23:59:07
【问题描述】:

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

tweet, date, id, username, compoundScore

我想计算某些关键字的平均值并按日期对结果进行分组,但我有点卡住了(仍然是一个 sql 'newb')。在我的脑海中,它看起来像下面这样。

需要一些指导 - 谢谢!

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

【问题讨论】:

    标签: mysql join group-by nested-queries


    【解决方案1】:

    您可以试试这个伙伴,而不是使用nested select

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

    【讨论】:

      【解决方案2】:

      您可以使用avgcase when 来执行此操作:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-03
        • 2013-08-18
        • 1970-01-01
        • 2018-05-08
        • 2013-01-19
        相关资源
        最近更新 更多