MySQL:从两个范围的平均值计算百分比变化

时间:2012-03-15 13:50:43

标签: mysql

我正在尝试计算日期范围A的平均值与日期范围B之间的百分比变化。

例如,网站在日期范围A中有100个访问者,在日期范围B中有200个访问者,增加了100%。

值存储在一个表中。

编辑:访问值存储在一个表中,URL存储在第二个表中,该表包含URL和用于连接两个表的id。

我的查询是:

SELECT urls.url, DATE_FORMAT(test.timestamp, '%Y %m %d') AS timestamp,
(SELECT test.visits 
 FROM test, urls 
 WHERE test.url_id = urls.id 
 AND urls.url LIKE '%website%' 
 AND test.location LIKE '%gb%' 
 AND test.timestamp >='$startdate' 
 AND test.timestamp <= '$enddate'
) AS visitors1, 

(SELECT test.visits 
 FROM test, urls 
 WHERE test.url_id = urls.id 
 AND urls.url LIKE '%website%' 
 AND test.location LIKE '%gb%' 
 AND test.timestamp >= DATE_SUB('$startdate', INTERVAL
     DATEDIFF('$enddate','$startdate') DAY) 
 AND test.timestamp <= DATE_SUB('$enddate', INTERVAL
     DATEDIFF('$enddate','$startdate') DAY)
) AS visitors2
FROM test, urls 
WHERE test.url_id = urls.id 
AND urls.url LIKE '%website%' 
AND test.location LIKE '%gb%'

编辑:更正了示例查询中的错误

我知道我需要添加类似的内容:

(visitors1 - visitors2) / visitors2 *100

我只是不确定在哪里

编辑:我正在构建一个仪表板,所需的输出是

网址|访问范围1 |访问范围2 |百分比变化

example.com | 100 | 200 | 100%

为原始帖子中的错误道歉。

1 个答案:

答案 0 :(得分:0)

只需将整个select包含在另一个select内,然后使用别名访问结果列。

/*Outer select*/
SELECT 
  q.url, q.`timestamp`, q.visitors1, q.visitors2
  , (q.visitors1 - q.visitors2) / (q.visitors2+0.00001) *100 AS percentage
FROM (
/*Inner select*/
SELECT 
  url
  , DATE_FORMAT(`timestamp`, '%Y %m %d') AS `timestamp`      
  , (SELECT visits 
     FROM test t
/*note the use of explicit inner joins*/ 
     INNER JOIN urls u ON (t.url_id = u.id)  
      WHERE url LIKE '%website%' AND location LIKE '%gb%' 
/*instead of >= and <= you can use `between` it's shorter to type.*/
      AND timestamp BETWEEN '$startdate' AND '$enddate') AS visitors1
  , (SELECT visits 
     FROM pagetest p
     INNER JOIN urls u ON (p.url_id = u.id) 
      WHERE u.url LIKE '%icis%com%' 
        AND p.f_TTFB < p.f_render 
        AND location LIKE '%gb%' 
        AND `timestamp` BETWEEN 
            DATE_SUB('$startdate', INTERVAL DATEDIFF('$enddate','$startdate') DAY) 
        AND DATE_SUB('$enddate', INTERVAL DATEDIFF('$enddate','$startdate') DAY)) 
    AS visitors2
FROM test
/* looks like you've got a missing join in the above FROM clause */ 
WHERE url_id = id AND url LIKE '%website%' AND location LIKE '%gb%'
/*Note that you need to supply each inner select with an alias*/
) AS q
/*I've used "q" here*/

注意,请不要使用隐式SQL'89连接语法,而是使用显式SQL'92连接。 它们更容易调试,因为连接条件和过滤条件不会混合在一起。