Я предположил, что вы хотите суммировать значения qta_finale, где id для конкретной testa меньше, чем max (id) для этой testa, и что последний id содержит id_articlo для выполнения требования присоединения к distinta_base.
drop table if exists raggruppamento;
create table raggruppamento (id int,testa int,articlo int,finale int);
insert into raggruppamento values
(30,45,918,2000),(31,45,918,2000),
(63,61,2059,5),(74,69,2056,8),(75,69,1366,9),
(76,65,2056,50),(77,65,2056,20),(78,65,2059,5);
drop table if exists distinta_base;
create table distinta_base(id int,id_articlo int,id_articlo_db int, qta int);
insert into distinta_base values
(5394,2056,2055,1),(5395,2056,2054,2),(5417,2056,2059,2),
(5398,2059,2060,1),(5399,2059,2061,2),(5406,2059,2062,2);
select r.*,r2.*,d.*,
r2.finale + (r.finale1 * d.qta) fbb
from
(
select r1.testa test1,max(r1.articlo) articlo1, sum(r1.finale) finale1
from raggruppamento r1
where r1.id <> (select max(r2.id) from raggruppamento r2 where r2.testa = r1.testa)
group by r1.testa
) r
join raggruppamento r2 on r2.testa = r.test1 and r2.id = (select max(r2.id) from raggruppamento r2 where r2.testa = r.test1)
join distinta_base d on d.id_articlo = r.articlo1 and d.id_articlo_db = r2.articlo
+-------+----------+---------+------+-------+---------+--------+------+------------+---------------+------+------+
| test1 | articlo1 | finale1 | id | testa | articlo | finale | id | id_articlo | id_articlo_db | qta | fbb |
+-------+----------+---------+------+-------+---------+--------+------+------------+---------------+------+------+
| 65 | 2056 | 70 | 78 | 65 | 2059 | 5 | 5417 | 2056 | 2059 | 2 | 145 |
+-------+----------+---------+------+-------+---------+--------+------+------------+---------------+------+------+
1 row in set (0.00 sec)
Есть ли только 2 идентификатора для каждого id_raggruppamento_testa? Обратите внимание, что вы скорее получите быстрый ответ, если вы замените изображения текстом. –
нет, может быть больше 2 –
Можете ли вы расширить свой пример, чтобы проиллюстрировать, как выглядела бы raggruppamento, если было больше 2, и объясните логику выбора 5417 из distinta_base. –