mysql查询与sum throgh 2表

时间:2017-01-03 08:50:32

标签: mysql join

我需要为distinta_base获取全部(qtaraggruppamento * qta_finaledistinta_base)和id_articoloraggruppamentoid_articolo中包含。raggruppamento

解释我报告我的表格,查询和结果:

表:raggruppamento

enter image description here

有这样的记录: enter image description here

和表distinta_baseenter image description here enter image description here

我的疑问:

SELECT a2.codice AS articolo_codice_db, a2.descrizione AS articolo_db_descrizione, a2.qta_min, a2.qta_max, a2.distinta_base, adb.id_articolo_db AS id_articolo_db, SUM(rp.qta_finale * adb.qta) AS qta_fabb 
FROM raggruppamento AS rp 
JOIN distinta_base AS adb ON adb.id_articolo = rp.id_articolo 
JOIN articolo AS a2 ON a2.id = adb.id_articolo_db
WHERE rp.id_raggruppamento_testa = 65 
GROUP BY id_articolo_db

我错了结果:

enter image description here

id_articolo_db -> 2059' s qta应为:5 +(50 * 2)= 105

enter image description here

1 个答案:

答案 0 :(得分:0)

我假设您希望将qta_finale值相加,其中特定testa的id小于该testa的max(id),并且最后一个id包含id_articlo以满足distinguishedta_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)