select
year(date),
sum(`index`.`index`),
substring_index(group_concat(`index`.`index` order by date asc), ',', -1) as last
from
where id_uin = 4 and id_status = 5 group by year(date);
если у вас версия mysql поддерживает оконные функции - можно через них
Самый
простой и тупой вариант получить желаемый вами результат в sql а не в приложении
select
(select `index` from `index` where year(date) = '2018' and id_uin = 4 and id_status = 5 order by date desc limit 1 ) as '2018',
(select `index` from `index` where year(date) = '2019' and id_uin = 4 and id_status = 5 order by date desc limit 1 ) as '2019',
(select `index` from `index` where year(date) = '2020' and id_uin = 4 and id_status = 5 order by date desc limit 1 ) as '2020',
(select `index` from `index` where year(date) = '2021' and id_uin = 4 and id_status = 5 order by date desc limit 1 ) as '2021';
если дорабатывать именно
ваш запрос
select
substring_index(group_concat(`2018`), ',', -1) as `2018`,
substring_index(group_concat(`2019`), ',', -1) as `2019`,
substring_index(group_concat(`2020`), ',', -1) as `2020`,
substring_index(group_concat(`2021`), ',', -1) as `2021`
from (SELECT
CASE WHEN date BETWEEN '2018-01-01' AND '2018-12-31' THEN `index` ELSE null END AS `2018`,
CASE WHEN date BETWEEN '2019-01-01' AND '2019-12-31' THEN `index` ELSE null END AS `2019`,
CASE WHEN date BETWEEN '2020-01-01' AND '2020-12-31' THEN `index` ELSE null END AS `2020`,
CASE WHEN date BETWEEN '2021-01-01' AND '2021-12-31' THEN `index` ELSE null END AS `2021`
FROM `index`
WHERE id_uin = 4 and id_status = 5
GROUP BY `2018`, `2019`, `2020`, `2021`) as t;