合并两个使用日期间隔,组和SUM的SQL查询

时间:2016-11-23 15:24:26

标签: mysql sql

首先,先谢谢你。

我正在处理2个查询,因为我想比较上周和前一周......

上周出场

SELECT keyword,
    SUM(users_desktop) AS desktop_last_week
FROM js 
    WHERE country='US' 
    AND  day >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY 
    AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY 
GROUP BY keyword
ORDER BY desktop_last_week DESC 
LIMIT 10;

前一周

SELECT keyword,
    SUM(users_desktop) AS desktop_previous_week
FROM js 
    WHERE country='US' 
    AND  day >= curdate() - INTERVAL DAYOFWEEK(curdate())+12 DAY 
    AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-7 DAY 
GROUP BY keyword
ORDER BY desktop_previous_week DESC 
LIMIT 10;

我想要做的是组合这些查询,以便我可以通过对desktop_last_week / desktop_this_week的划分进行ORDER BY来查找趋势上升的关键字(即:本周搜索的内容比上周多得多)

关于如何将这些结合在一起的任何想法?

3 个答案:

答案 0 :(得分:1)

这称为条件聚合。使用现有查询中的where子句来执行此操作。

SELECT keyword, 
       Sum(CASE 
             WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+6 day 
                  AND day < Curdate() - INTERVAL Dayofweek(Curdate())-1 day THEN 
             users_desktop 
             ELSE 0 
           end) AS desktop_last_week, 
       Sum(CASE 
             WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+12 day 
                  AND day < Curdate() - INTERVAL Dayofweek(Curdate())-7 day THEN 
             users_desktop 
             ELSE 0 
           end) AS desktop_prev_last_week 
FROM   js 
WHERE  country = 'US' 
GROUP  BY keyword 
ORDER  BY desktop_prev_last_week / desktop_this_week DESC 
LIMIT  10 

答案 1 :(得分:0)

使用联盟! 你可以得到2个查询。如果您想订购,那么将其放入子查询

答案 2 :(得分:0)

您可以展开where子句以包含两个时间范围,并将它们之间的区分逻辑移到总和内的case表达式。顺便说一句,使用between运算符而不是&gt; =和&lt;对将使查询本身更容易阅读:

SELECT    keyword,
          SUM(CASE WHEN day BETWEEN 
                        (CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 6 DAY) AND
                        (CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 1 DAY) 
                    THEN users_desktop 
               END) AS desktop_last_week,
          SUM(CASE WHEN day BETWEEN 
                        (CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 12 DAY) AND
                        (CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 7 DAY) 
                    THEN users_desktop 
               END) AS desktop_previous_week
FROM     js 
WHERE    country = 'US' 
GROUP BY keyword
ORDER BY desktop_last_week DESC, desktop_previous_week DESC
LIMIT    10;