我有一个mysql表,用于存储租赁系统的每日价格。表格包含ID,Property_id,日期和价格
id 1 | propertyid 1 | date 2015-05-01 | price 300
id 2 | propertyid 1 | date 2015-05-02 | price 300
id 3 | propertyid 1 | date 2015-05-03 | price 300
id 4 | propertyid 1 | date 2015-05-04 | price 300
id 5 | propertyid 1 | date 2015-05-05 | price 500
id 6 | propertyid 1 | date 2015-05-06 | price 500
id 7 | propertyid 1 | date 2015-05-07 | price 700
id 6 | propertyid 1 | date 2015-05-08 | price 900
id 7 | propertyid 1 | date 2015-05-09 | price 900
我得到的结果
( SELECT * from price WHERE property_id = 1 ORDER BY date ASC)
问题是,我需要将价格与相同日期的开始日期和结束日期分组,但是我不知道如何开始以及如何开始。结果应该像
startdate = 2015-05-01 enddate = 2015-05-05 price = 300
startdate = 2015-05-05 enddate = 2015-05-07 price = 500
startdate = 2015-05-07 enddate = 2015-05-08 price = 700
startdate = 2015-05-08 enddate = 2015-05-10 price = 900
这样我可以获得一年的所有价格,但是如果价格在一系列日期中相同,则可以将它们分组。我在foreach中获得了所有值,但不知道如何对它们进行分组。
谢谢。
这是在php中实现的方法。
首先,将所有返回的数据库行保存到数组中
while($row = fetchRow()){
$rows[] = $row;
}
其次,创建一个数组来保存组,一个计数器var和最后一个行键。
$ranges=array();
$x=0;
$last=count($rows)-1;
第三,遍历每个返回的行,执行以下操作-设置范围起始日期/价格。如果是最后一行,则设置结束日期;否则,设置结束日期。否则,如果下一行的价格不同,则设置结束日期并增加计数器(对于单个日期范围);否则,如果价格与当前区间价格不同,则设置结束日期并增加计数器。
foreach($rows as $key=>$row){
//if range startdate not set, create the range startdate and price
if(!isset($ranges[$x]['startdate'])){
$ranges[$x] = array('startdate'=>$row['startdate'], 'price'=>$row['price']);
}
//if the last row set the enddate
if($key==$last){
$ranges[$x]['enddate'] = $row['startdate'];
}
//if the next price is not the same, set the enddate and increase the counter (single date range)
else if($row['price']!=$rows[$key+1]['price'] ){
$ranges[$x]['enddate'] = $row['startdate'];
$x++;
}
//if the price is not the same as the current range price, set the enddate and increase the counter
else if($row['price']!=$ranges[$x]['price'] ){
$ranges[$x]['enddate'] = $rows[$key-1]['startdate'];
$x++;
}
}
最后,遍历您的范围并打印值
foreach($ranges as $range){
echo "startdate = {$range['startdate']} enddate = {$range['enddate']} price = {$range['price']}<br />";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句