[Solved] How create sum from tabel 2 and show data tabel 1 and tabel 2 [closed]


On MySQL 8+, we can handle this without a subquery by using analytic functions:

SELECT
    b.id,
    a.invoice,
    b.price AS total,
    SUM(b.price) OVER (PARTITION BY a.id) AS count
FROM TableB b
LEFT JOIN TableA a
    ON a.id = b.aid;

On earlier versions of MySQL, or if you are doing this from an ORM layer which doesn’t like analytic functions, we can also try using a join to aggregate the counts:

SELECT
    b1.id,
    a.invoice,
    b1.price AS total,
    COALESCE(b2.count, 0) AS count
FROM TableB b1
LEFT JOIN TableA a
    ON a.id = b1.aid
LEFT JOIN
(
    SELECT aid, SUM(price) AS count
    FROM TableB
    GROUP BY aid
) b2
    ON b2.aid = b1.aid;

0

solved How create sum from tabel 2 and show data tabel 1 and tabel 2 [closed]