Как взять первое и последнее значение из данных?
Есть таблица. Этот диапазон я хочу разбить по index, и взять из него первое значение и последнее.
datetime,index
1633378385000,4
1633378451000,4
1633378505000,4
1633378582000,4
1633378652000,4
1633378717000,4
1633378782000,""
1633378848000,""
1633378913000,""
1633383874000,""
1633383940000,5
1633384007000,5
1633384011000,5
1633384205000,5
1633384266000,5
1633384340000,5
1633387730000,""
1633387750000,""
1633388380000,4
1633389103000,4
1633389181000,4
1633389247000,4
На выходе должно получиться
1633378385000,4
1633378717000,4
1633383940000,5
1633384340000,5
1633388380000,4
1633389247000,4
Думал сделать с помощью first_value - last_value, но оно смотрит по всей таблице, а мне нужно по кусочкам.
Ответы (1 шт):
Автор решения: Akina
→ Ссылка
Решение для MySQL версии 8+:
WITH
cte1 AS ( SELECT *, `index` <> LAG(`index`) OVER (ORDER BY `datetime`) newgroup
FROM test ),
cte2 AS ( SELECT *, COALESCE(SUM(newgroup) OVER (ORDER BY `datetime`), 0) groupnum
FROM cte1 )
SELECT MIN(`datetime`) datetime_start,
MAX(`datetime`) datetime_end,
ANY_VALUE(`index`) `index`
FROM cte2
WHERE `index`
GROUP BY groupnum
ORDER BY 1;
или
WITH
cte AS ( SELECT *,
COALESCE(LAG(`index`) OVER (ORDER BY `datetime`), '') previousindex,
COALESCE(LEAD(`index`) OVER (ORDER BY `datetime`), '') nextindex
FROM test )
SELECT `datetime`, `index`
FROM cte
WHERE '' IN (previousindex, nextindex)
AND `index` <> ''
ORDER BY 1;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e6104479de1664121d560f2629c3a3b5
PS. Задача стандартная, называется "Gaps and islands".
