MySQL - 总计数&单个SQL查询中的更改率

时间:2016-01-27 06:55:34

标签: mysql sql

我试图提取网站点击总数加上每个城市每天每个客户的变化率(增加/减少率),作为单个SQL查询中的百分比但不能正确。

我在

创建了一个示例
  

http://www.sqlfiddle.com/#!9/fd279/8

我可以请求协助吗?

3 个答案:

答案 0 :(得分:1)

尝试避免内连接,无论如何都有错误的条件(t1.hitDate = t2.hitDate and t1.hitDate-1 = t2.hitDate无法满足):

select 
  t1.HitDate,
  t1.City,
  t1.Client,
  SUM(t1.NumVisits)  -   IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0)  as rate_of_change
from
  PAGE_HITS t1
WHERE
t1.Client='C'
 group by
   HitDate,
   City
   ORDER BY HitDate;

答案 1 :(得分:0)

获得基于百分比的增加/减少

select 
  t1.HitDate,
  t1.City,
  t1.Client,
    SUM(t1.NumVisits),
  IFNULL(((SUM(t1.NumVisits)  -   IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0)) * 100) / IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0),0)  as rate_of_change
from
  PAGE_HITS t1
WHERE
t1.Client='C'
 group by
   HitDate,
   City
   ORDER BY HitDate;

答案 2 :(得分:0)

首先制作一个像rownum这样的唯一编号 并进行相同的查询 并加入rownum列 然后你可以看到前一个月作为新列并计算变化率。

SELECT  A.HitDate, A.City, A.sumThis, B.sumFormer, (A.sumThis / B.sumFormer - 1) * 100 as 'ChangingRate'
From    (
        select @rownum1:=@rownum1 + 1 as 'rownum1', HitDate, City, sum(NumVisits) as 'sumThis'
        from page_hits, (Select @rownum1:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) A
Left Join (
        select @rownum2:=@rownum2 + 1 as 'rownum2', HitDate, City, sum(NumVisits) as 'sumFormer'
        from page_hits, (Select @rownum2:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) B On A.rownum1 - 1 = B.rownum2