【问题标题】:mysql query with sum throgh 2 tables通过2个表进行总和的mysql查询
【发布时间】:2017-01-03 08:50:32
【问题描述】:

我需要获取所有 (distinta_base.qta*raggruppamento.qta_finale) 和 distinta_base.id_articolo 以获取表中包含的每个raggruppamento.id_articolo raggruppamento

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

表:raggruppamento

使用此记录:

还有表distinta_base

我的查询:

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

我的错误结果:

id_articolo_db -> 2059 的 qta 应该是:5 + (50 * 2) = 105

【问题讨论】:

  • 每个 id_raggruppamento_testa 是否只有 2 个 id?请注意,如果您将图像替换为文本,您更有可能得到快速响应。
  • 不,可能超过 2
  • 您能否扩展您的示例以说明如果 raggruppamento 超过 2 个时的外观,并解释从 distinta_base 中选择 5417 的逻辑。

标签: mysql join


【解决方案1】:

我假设您希望对 qta_finale 值求和,其中特定 testa 的 id 小于该 testa 的 max(id) 并且最后一个 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)

【讨论】:

    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多