I have a table with a date column and a price column. The date column has a row for each day of the year.
The table is like this:
2017-09-01 158.00
2017-09-02 158.00
2017-09-03 158.00
2017-09-04 158.00
etc.
2017-09-10 175.00
2017-09-11 175.00
etc.
2017-10-20 158.00
2017-10-21 158.00
I want to get the first date and last date in a time range that has same price.
So the result for above should be:
2017-09-01 -- 2017-09-04 158 euro.
2017-09-10 -- 2017-09-11 175 euro.
2017-10-20 -- 2017-10-21 158 euro.
See if this works for you. It's based on another answer I gave here. You loop through the days, accumulating every day that has the same price as before in an array. Every time the loop detects a change in the price, a new array is created, and so on.
<?php
$values[] = ["2017-09-01", "158.00"];
$values[] = ["2017-09-02", "158.00"];
$values[] = ["2017-09-03", "158.00"];
$values[] = ["2017-09-04", "158.00"];
$values[] = ["2017-09-10", "175.00"];
$values[] = ["2017-09-11", "175.00"];
$values[] = ["2017-10-20", "158.00"];
$values[] = ["2017-10-21", "158.00"];
$values[] = ["2017-10-22", "159.00"];
$values[] = ["2017-10-23", "152.00"];
$values[] = ["2017-10-24", "152.00"];
$ult = null;
$currentRange = [];
$ranges = [];
foreach ($values as $fecha) {
$day = $fecha[0];
$price = $fecha[1];
if ($ult === null) {
$currentRange = [
"price" => $price,
"days" => [$day]
];
}
else {
if ($price === $ult) {
$currentRange["days"][] = $day;
}
else {
$ranges[] = $currentRange;
$currentRange = [
"price" => $price,
"days" => [$day]
];
}
}
$ult = $price;
}
$ranges[] = $currentRange;
$rangesString = [];
foreach ($ranges as $range) {
$str = $range["days"][0];
if (count($range["days"]) > 1) {
$str .= " - ".$range["days"][count($range["days"]) - 1];
}
$str .= ": ".$range["price"];
$rangesString[] = $str;
}
echo (implode("<br>", $rangesString));
/* results:
2017-09-01 - 2017-09-04: 158.00
2017-09-10 - 2017-09-11: 175.00
2017-10-20 - 2017-10-21: 158.00
2017-10-22: 159.00
2017-10-23 - 2017-10-24: 152.00
*/
If your date column is Dte and amount column is amt then your query should be like this
SELECT MIN(Dte), MAX(Dte), CONCAT(amt,' euro') FROM test
GROUP BY amt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.