简体   繁体   English

每天SQL总点击数并计算百分比变化

[英]SQL sum hits per day and calculate percentage change

I have a single table with a list of hits/downloads, every row has of course a date. 我有一个表格,其中列出了点击量/下载量,每行当然都有一个日期。 I was able to sum all the rows grouped by day. 我能够汇总按天分组的所有行。

Do you think it's possible to also calculate the change in percentage of every daily sum compared to the previous day using a single query, starting from the entire list of hits? 您认为是否也可以使用单个查询从整个匹配列表中计算出每日总金额与前一天相比的百分比变化?

I tried to do this 我试图做到这一点

select *, temp1.a-temp2.b/temp1.a*100 as percentage from
(select DATE(date), count(id_update) as a from vas_updates group by DATE(date)) as table1
 UNION
(select DATE_ADD(date, INTERVAL 1 DAY), count(id_update) as b from vas_updates group by DATE(date)) as table2, vas_updates

but it won't work (100% CPU + crash). 但它不起作用(100%CPU +崩溃)。 Of course I can't JOIN them because those two temp tables share nothing in common being with 1 day offset. 当然,我不能加入它们,因为这两个临时表在1天的偏移量下没有任何共同点。

The table looks like this, nothing fancy. 桌子看起来像这样,没什么花哨的。

id_updates | date
1            2014-07-06 12:45:21
2            2014-07-06 12:46:10
3            2014-07-07 10:16:10

and I want 而且我要

date       | sum a | sum b | percentage
2014-07-07   2       1       -50%

It can be either be positive or negative obviously 显然可以是正数或负数

select DATE(v.date), count(v.id_update) a, q2.b, count(v.id_update) - q2.b/count(v.id_update)*100 as Percentage
from vas_updates v
Left Join (select DATE_ADD(date, INTERVAL 1 DAY) d2, count(id_update) as b 
           from vas_updates group by d2) as q2
ON v.date = q2.d2
group by DATE(v.date)

The sum by day is: 每天的总和是:

select DATE(date), count(id_update) as a
from vas_update
group by DATE(date);

In MySQL, the easiest way to get the previous value is by using variables, which looks something like this: 在MySQL中,获得先前值的最简单方法是使用变量,它看起来像这样:

select DATE(u.date), count(u.id_update) as cnt,
       @prevcnt as prevcnt, count(u.id_update) / @prevcnt * 100,
       @prevcnt := count(u.id_update)
from vas_update u cross join
     (select @prevcnt := 0) vars
group by DATE(u.date)
order by date(u.date);

This will generally work in practice, but MySQL doesn't guarantee the ordering of variables. 这通常会在实践中起作用,但是MySQL不保证变量的顺序。 A more guaranteed approach looks like: 一种更有保证的方法如下所示:

select dt, cnt, prevcnt, (case when prevcnt > 0 then 100 * cnt / prevcnt end)
from (select DATE(u.date) as dt, count(u.id_update) as cnt,
             (case when (@tmp := @prevcnt) is null then null
                   when (@prevcnt := count(u.id_update)) is null then null
                   else @tmp
              end) as prevcnt
      from vas_update u cross join
           (select @prevcnt := 0, @tmp := 0) vars
      group by DATE(u.date)
      order by date(u.date)
     ) t;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM