[英]mysql get first and last entry with same value in other column
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 如果您的日期列为Dte且金额列为amt,则您的查询应如下所示
SELECT MIN(Dte), MAX(Dte), CONCAT(amt,' euro') FROM test
GROUP BY amt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.