我有一个包含日期列和价格列的表格。 日期列每年的每一天都有一行。
表格如下:
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
我希望在价格相同的时间范围内获得第一个日期和最后一个日期。
所以上面的结果应该是:
2017-09-01 -- 2017-09-04 158 euro.
2017-09-10 -- 2017-09-11 175 euro.
2017-10-20 -- 2017-10-21 158 euro.
答案 0 :(得分:1)
看看这是否适合您。这是基于我在这里给出的另一个答案。你循环遍历这些日子,累积每天与数组中价格相同的价格。每次循环检测到价格变化时,都会创建一个新数组,依此类推。
<?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
*/
答案 1 :(得分:0)
如果你的日期列是Dte,而amount列是amt,那么你的查询应该是这样的
SELECT MIN(Dte), MAX(Dte), CONCAT(amt,' euro') FROM test
GROUP BY amt