mysqlphp将开始日期和结束日期与价格进行分组


mysql php grouping start date and end date with price

我有一个mysql表,用于存储租赁系统的每日价格。表具有id、属性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;

第三,循环遍历每个返回的行,执行以下操作-设置startdate/price范围。如果是最后一行,则设置结束日期;否则,如果下一行价格不相同,则设置结束日期并增加计数器(针对单个日期范围);否则,如果价格与当前范围价格不同,请设置结束日期并增加计数器。

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 />";
}