我的表:
id | views | date
1 | 100 | 2017-03-09
2 | 150 | 2017-03-10
3 | 300 | 2017-03-11
4 | 350 | 2017-03-12
我需要计算这样的天数之间的访问次数差异
2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50
2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150
2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50
and so on...
我设法得到了类似的结果,但并不是我想要的那样
$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$t = $row['views'];
$dat = $row['date'];
$sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
$result1 = mysql_query($sql1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$y = $row1['views'];
$dat1 = $row1['date'];
$d = $t-$y;
echo "{$dat}-->Visitors:{$t}";
echo "<br/>";
echo "{$dat1}-->Visitors:{$y}";
echo "<br/>";
echo "Difference between days:{$d}";
echo "<br/><br/><br/>";
}
}
所以我想我需要用一个查询选择两次相同的表。
答案 0 :(得分:1)
这里不需要SQL杂技。
您正在按日期顺序显示行。只需将变量中最后一行的计数保留在变量中,在php中减去,你就有了不同之处。
删除嵌套循环。你只需要一个循环。
$last_views = null;
while($row = mysql_fetch_array($result))
{
$views = $row['views'];
$dat = $row1['date'];
if( $last_views === null )
$delta_views = "";
else
$delta_views = $last_views - $views;
$last_views = $views;
echo "{$dat}-->Visitors:{$views}";
echo "<br/>";
echo "Difference between days:{$delta_views}";
echo "<br/>";
}
答案 1 :(得分:0)
按日期分组和排序。然后,您可以使用变量将最后一个视图值存储在其中,并将其与当前视图值进行比较。
select date,
sum(views) as currentViews
sum(views) - @previous as viewsDiff,
@previous := sum(views)
from your_table
cross join (select @previous:= 0) p
group by date
order by date
答案 2 :(得分:0)
尝试在MySQL中处理它。
http://rextester.com/XXJWR75843
set @views1=0;
select t.* ,views-lag_views from (
select t1.*,@views1 lag_views , @views1:=views curr_views
from Table1 t1
) t
但是你需要想办法忽略第一个值,因为它给你的值与views
相同。
感谢此answer复制滞后函数。