我有单独的日期和价值表。我想显示日期差异和价值。
表
date | value
-------------------------
7/24/2015 496
7/31/2015 496
8/7/2015 496
8/14/2015 496
8/21/2015 496
8/28/2015 400
9/4/2015 400
9/11/2015 400
1/29/2016 400
2/5/2016 400
输出
date | Difference | value
-------------------------
7/24/2015 496
8/28/2015 96 400
9/11/2015 400
条件: 1.如果根据日期在差异栏中显示的价值有任何差异。 2.重复相同的值不需要再次显示。 3.减少将显示另一列的差异。
CREATE TABLE IF NOT EXISTS `account_str1` (
`Date` date NOT NULL,
`acc_no` varchar(255) NOT NULL,
`cust_name` varchar(255) NOT NULL,
`points` int(11) NOT NULL
)
// cdsl_res taken as array count
<table class="table-bordered table-striped table">
<thead>
<th>Date </th>
<th>Transferred </th>
<th>Points </th>
</thead>
<?php
for($i=0;$i<$cdsl_res;$i++){
echo '<tr>';
echo '<td>'.$mydateArray[$i].'</td>';
$share1 = $mypositionArray[$i];
$share2 = $mypositionArray[$i-1];
if($share_1 < $share_2){
$diff = $share_2 - $share_1;
echo '<td>'.$diff.'</td>';
}
else{
echo '<td></td>';
}
echo '<td>'.$mypositionArray[$i].'</td>';
echo '</tr>';
}
?>
答案 0 :(得分:0)
您可以通过查看前一个值和一行中的值数来执行此操作。在MySQL中,一种方法是使用相关子查询。其余的只是where
子句中的逻辑:
select date,
(case when value <> prev_value then prev_value - value end) as diff,
value
from (select a.*,
(select value
from account_str1 a2
where a2.date < a.date
order by a2.date desc
limit 1
) as prev_value,
(select count(*)
from account_str1 a2
where a2.date <= a.date and a2.value = a.value
) as seqnum
from account_str1 a
) t
where prev_value is null or value <> prev_value or seqnum = 2;
答案 1 :(得分:0)
可以通过复杂的SQL查询来完成,如上一个答案中所建议的那样。但我认为PHP解决方案更容易。因为你无论如何都要逐个遍历所有记录。
$sql='SELECT `Date`, `points` FROM `account_str1` ORDER BY `Date`';
$q=$db->query($sql);
$prev=0;
while ($r=$q->fetch_assoc()) {
$dif = $r['points']>$prev?$r['points']-$prev:'';
$prev=$r['points'];
echo "<tr><td>$r[Date]</td><td>$dif</td><td>$r[points]</td></tr>\n";
}